/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *  
 */
// https://issues.jboss.org/browse/TEIID-2141
// https://issues.jboss.org/browse/TEIID-2311
// https://issues.jboss.org/browse/TEIID-2476
package org.teiid.dqp.internal.process;

import com.datavirtuality.dv.core.interfaces.DVCaller;
import com.datavirtuality.dv.core.services.DVServices;
import org.teiid.CommandContext;
import org.teiid.PolicyDecider;
import org.teiid.adminapi.DataPolicy;
import org.teiid.adminapi.DataPolicy.Context;
import org.teiid.adminapi.DataPolicy.PermissionType;
import org.teiid.adminapi.impl.DataPolicyMetadata;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

public class DataRolePolicyDecider implements PolicyDecider {

    private boolean allowCreateTemporaryTablesByDefault = true;
    private boolean allowFunctionCallsByDefault = false;
	private boolean allowReadByChildren = false;

	@Override
	public Set<String> getInaccessibleResources(PermissionType action,
			Set<String> resources, Context context, CommandContext commandContext) {
		if (commandContext.getUserName().equals("system@dv-security") || commandContext.getUserName().equals("system")) {
			return Collections.emptySet();
		}		
		if (action == PermissionType.EXECUTE && context == Context.FUNCTION && allowFunctionCallsByDefault) {
			return Collections.emptySet();
		}
        resources.removeIf(resource -> DVServices.callne(DVProcedurePolicyIntf.class, s -> s.isProcAllowed(commandContext, resource), false));
		resources.removeIf(resource -> DVServices.callne(DVFunctionPolicyIntf.class, s -> s.isFunctionAllowed(commandContext, resource), false));
		Collection<DataPolicy> policies = commandContext.getAllowedDataPolicies().values();
		int policyCount = policies.size();
		Boolean optionEnabled = (Boolean) DVCaller.call(177);
		boolean oldWay = optionEnabled != null && optionEnabled;
		if (oldWay) {
			outer:for (Iterator<String> iter = resources.iterator(); iter.hasNext();) {
				String resource = iter.next();
				Iterator<DataPolicy> policyIter = policies.iterator();
				boolean storedNotAllowed = false;
				boolean resourceIsAllowed = false;
				for (int j = 0; j < policyCount; j++) {
					DataPolicyMetadata policy = (DataPolicyMetadata)policyIter.next();
					if (policy.isGrantAll()) {
						resources.clear();
						return resources;
					}
					String resourceToCheck = resource;
					String resourceType = resource.contains(":") ? resource.substring(0, resource.indexOf(':')) : context.getResourceType();
					resourceToCheck = (resourceType != null && !resourceToCheck.contains(":")) ? (resourceType + ":" + resourceToCheck) : resourceToCheck;
					while (resourceToCheck.length() > 0) {
						boolean isFalse = false;
						Boolean allows = allows(resourceToCheck, action, policy);
						if (allows != null) {
							if (allows) {
								iter.remove();
								continue outer;
							}
							isFalse = true;
							storedNotAllowed = true;
						}
						if (isFalse || (action == PermissionType.LANGUAGE && !resourceToCheck.contains(":"))) {
							break; // don't check less specific permissions
						}
						if ("*".equals(resourceToCheck)) {
							if (commandContext.isAllowResourcesByParent()) {
								resourceIsAllowed = true;
							}
							break;
						}
						resourceToCheck = DataPolicyMetadata.getResourceOneLevelUp(resourceToCheck, resourceType);
					}
				}
				if (resourceIsAllowed && !storedNotAllowed) {
					iter.remove();
				}
			}
			return resources;
		}
		for (Iterator<String> iter = resources.iterator(); iter.hasNext();) {
			String resource = iter.next();
			Iterator<DataPolicy> policyIter = policies.iterator();
			boolean storedAllows = false;
			boolean storedNotAllowed = false;
			boolean resourceIsAllowed = false;
			int storedSpecific = -1;
			outer:for (int j = 0; j < policyCount; j++) {
				DataPolicyMetadata policy = (DataPolicyMetadata)policyIter.next();
				if (policy.isGrantAll()) {
					resources.clear();
					return resources;
				}
				String resourceToCheck = resource;
				String resourceType = resource.contains(":") ? resource.substring(0, resource.indexOf(':')) : context.getResourceType();
				resourceToCheck = (resourceType != null && !resourceToCheck.contains(":")) ? (resourceType + ":" + resourceToCheck) : resourceToCheck;
				int specific = 0;
				while (resourceToCheck.length() > 0) {
					boolean isFalse = false;
					Boolean allows = allows(resourceToCheck, action, policy);
					if (allows != null) {
						if (storedSpecific < 0 || storedSpecific > specific) {
							storedAllows = allows;
							storedSpecific = specific;
						}
						if (allows) {
							continue outer;
						}
						isFalse = true;
						storedNotAllowed = true;
					}
					if (isFalse || (action == PermissionType.LANGUAGE && !resourceToCheck.contains(":"))) {
						break; // don't check less specific permissions
					}
					if ("*".equals(resourceToCheck)) {
						if (commandContext.isAllowResourcesByParent()) {
							resourceIsAllowed = true;
						}
						break;
					}
					resourceToCheck = DataPolicyMetadata.getResourceOneLevelUp(resourceToCheck, resourceType);
					specific++;
					if (resourceToCheck.isEmpty())
						resourceToCheck = "*";
				}
			}
			if (storedAllows || (resourceIsAllowed && !storedNotAllowed)) {
				iter.remove();
			}
		}
		return resources;
	}

	private Boolean allows(String resourceToCheck, PermissionType action, DataPolicyMetadata policy) {
		if (allowReadByChildren && action == PermissionType.READ) {
			return policy.allowsToReadByResourceOrChildren(resourceToCheck);
		}
		return policy.allows(resourceToCheck, action);
	}

	@Override
	public boolean hasRole(String roleName, CommandContext context) {
		return context.getAllowedDataPolicies().containsKey(roleName);
	}

	@Override
	public boolean isTempAccessible(PermissionType action, String resource,
			Context context, CommandContext commandContext) {
		Boolean result = null;
    	for(DataPolicy p:commandContext.getAllowedDataPolicies().values()) {
			DataPolicyMetadata policy = (DataPolicyMetadata)p;
			if (policy.isGrantAll()) {
				return true;
			}
			if (policy.isAllowCreateTemporaryTables() != null) {
				if (policy.isAllowCreateTemporaryTables()) {
					return true;
				}
				result = policy.isAllowCreateTemporaryTables();
			}
		}
    	if (result != null) {
    		return result;
    	}
    	return allowCreateTemporaryTablesByDefault;
	}
	
    public void setAllowCreateTemporaryTablesByDefault(
			boolean allowCreateTemporaryTablesByDefault) {
		this.allowCreateTemporaryTablesByDefault = allowCreateTemporaryTablesByDefault;
	}
    
    public void setAllowFunctionCallsByDefault(boolean allowFunctionCallsDefault) {
		this.allowFunctionCallsByDefault = allowFunctionCallsDefault;
	}

	@Override
	public void setAllowReadByChildren(boolean allowReadByChildren) {
		this.allowReadByChildren = allowReadByChildren;
	}

	@Override
    public boolean validateCommand(CommandContext commandContext) {
    	return !commandContext.getVdb().getDataPolicies().isEmpty();
    }

}
