/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
/*
 * Created on 18-Oct-2004
 *
 */
package uk.ac.ic.doc.kevlar.api.programs.arguments;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInfo.AbstractArgumentInfo;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInfo.BoolArgumentInfo;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInfo.SetArgumentInfo;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInfo.SetValue;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInstance.BoolArgumentValue;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.argumentInstance.SetArgumentValue;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.iomapping.AbstractArgumentCondition;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.iomapping.ArgumentStateIOMapping;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.iomapping.BoolArgumentCondition;
import uk.ac.ic.doc.kevlar.api.programs.arguments.internal.iomapping.SetArgumentCondition;
import uk.ac.ic.doc.kevlar.core.framework.typecheck.IInterfaceClass;
import uk.ac.ic.doc.kevlar.publicInterfaces.INode;
import uk.ac.ic.doc.kevlar.publicUtil.collections.IImmutableList;
import uk.ac.ic.doc.kevlar.publicUtil.collections.IImmutableMap;
import uk.ac.ic.doc.kevlar.publicUtil.collections.IImmutableSet;
import uk.ac.ic.doc.kevlar.publicUtil.collections.ImmutableArrayList;
import uk.ac.ic.doc.kevlar.publicUtil.collections.ImmutableHashMap;
import uk.ac.ic.doc.kevlar.publicUtil.collections.ImmutableHashSet;
import uk.ac.ic.doc.kevlar.publicUtil.dom.XMLUtil;

/**
 * 
 * @author Daniel Burke
 *
 */


public final class ArgumentModel implements IArgumentModel {
    
	private IImmutableSet<AbstractArgumentInfo> arguments;
	private IImmutableMap<String, IBasicArgumentInfo> argumentMap;
	private IImmutableSet<String> rootArguments;
	private IImmutableList<ArgumentStateIOMapping> mappings;
	private IImmutableSet<IInterfaceClass> dependancies;
	
	private ImmutableHashSet<IInputNode> emptyInputs = new ImmutableHashSet<IInputNode>(new HashSet<IInputNode>());
	private ImmutableHashSet<IOutputNode> emptyOutputs = new ImmutableHashSet<IOutputNode>(new HashSet<IOutputNode>());
	
	private class TypeCheckingVisitor implements IArgumentVisitor
	{
	    private IBasicArgumentInfo argInf;
	    private boolean error = false;
	    public TypeCheckingVisitor(IBasicArgumentInfo argInf)
	    {
	        this.argInf = argInf;
	    }

        public void setArgument(ISetArgumentInfo info) {
                error = info != argInf;
        }

        public void boolArgument(IBoolArgumentInfo info) {
            error = info != argInf;
        }

        public void singlelineArgument(ISinglelineArgumentInfo info) {
            error = info != argInf;
        }

        public void multilineArgument(IMultilineArgumentInfo info) {
            error = info != argInf;
        }
        
        public boolean wasError()
        {
            return error;
        }
	}
	
	public ArgumentModel(Collection<IBasicArgumentInfo> arguments, 
			List<IArgumentStateIOMapping> mappings)
	{
		if(arguments == null || mappings == null)
		{
			throw new IllegalArgumentException("Null parameters not allowed");
		}
		

		Set<AbstractArgumentInfo> tempArgs = new HashSet<AbstractArgumentInfo>();
		
		Map<String, IBasicArgumentInfo> tempArgMap = 
			new HashMap<String, IBasicArgumentInfo>();
		
		for(IBasicArgumentInfo arginf : arguments)
		{
		    TypeCheckingVisitor visitor = new TypeCheckingVisitor(arginf);
		    arginf.takeVisitor(visitor);
		    if(visitor.wasError())
		    {
		        throw new IllegalArgumentException("All arguments must" +
		                " be one of Bool/Set/Text" +
		                "ArgumentInfo");
		    }
		    
		    if(tempArgMap.containsKey(arginf.getName()))
		    {
		    	throw new IllegalArgumentException("There are at least two arguments " +
		    			"passed that share the same name");
		    }
		    
		    tempArgMap.put(arginf.getName(), arginf);
		    tempArgs.add((AbstractArgumentInfo)arginf);
		}
		
		this.argumentMap = new ImmutableHashMap<String, IBasicArgumentInfo>(tempArgMap);
		this.arguments = new ImmutableHashSet<AbstractArgumentInfo>(tempArgs);
		
		Set<IInterfaceClass> tempDependancies = new HashSet<IInterfaceClass>();
		List<ArgumentStateIOMapping> tempMappings = new ArrayList<ArgumentStateIOMapping>();
		
		for(IArgumentStateIOMapping mapping : mappings)
		{
			if(!(mapping instanceof ArgumentStateIOMapping))
			{
		        throw new IllegalArgumentException("All mappings must" +
		                " be ArgumentStateIOMapping");
			}
			
			for(INode node : mapping.getInputs())
			{
			    tempDependancies.add(node.getType().getTypeDependancy());
			}
			
			for(INode node : mapping.getOutputs())
			{
			    tempDependancies.add(node.getType().getTypeDependancy());
			}
			
			tempMappings.add((ArgumentStateIOMapping)mapping);
		}		
		
		this.mappings = new ImmutableArrayList<ArgumentStateIOMapping>(tempMappings);

		dependancies = new ImmutableHashSet<IInterfaceClass>(tempDependancies);
		
		rootArguments = validateModelAndGetRoots();
	}
	
	public IImmutableMap<String, IBasicArgumentInfo> getArgumentNameMap()
	{
		return argumentMap;
	}
	
	private Set<String> validateConditions()
	{
	    //TODO: Check that inputs and outputs don't swap around 
	    Set<String> nodeNames = new HashSet<String>();
	    
		for(IArgumentStateIOMapping basicMapping : mappings)
		{
			ArgumentStateIOMapping mapping = 
				(ArgumentStateIOMapping)basicMapping;
			
			for(IInputNode node : mapping.getInputs())
			{
			    nodeNames.add(node.getName());
			}
			
			for(IOutputNode node : mapping.getOutputs())
			{
			    nodeNames.add(node.getName());
			}			
			
			
			HashSet<String> found = new HashSet<String>();
			for(IBasicArgumentCondition basicCondition : mapping.getConditions())
			{
				AbstractArgumentCondition condition = 
					(AbstractArgumentCondition)basicCondition;
				
				String target = condition.getTargetArgument();
				if(!argumentMap.containsKey(target))
				{
					throw new IllegalStateException("All conditions must be on " +
							"valid targets. " + target +
							"is not in the argument list");	
				}
				
				if(found.contains(target))
				{
	 				throw new IllegalStateException("You have two conditions on " +
	 						target);
				}
				
				found.add(target);
				
				IBasicArgumentInfo basicArg = argumentMap.get(target);
				AbstractArgumentInfo arg = (AbstractArgumentInfo)basicArg;
				if(condition instanceof BoolArgumentCondition)
				{
					if(!(arg instanceof BoolArgumentInfo))
					{
						throw new IllegalStateException("Condition on " + target +
								" must not be of type bool as " + target +
								" is not a bool argument");
					}
				}
				else if(condition instanceof SetArgumentCondition)
				{ 
					if(!(arg instanceof SetArgumentInfo))
					{
						throw new IllegalStateException("Condition on " + target +
								" must not be of type set as " + target + 
								" is not a set argument");
					}
					else
					{
						SetArgumentCondition setCondition = (SetArgumentCondition)condition;
						SetArgumentInfo setArg = (SetArgumentInfo)arg;
						
						for(String allowed : setCondition.getAllowedValues())
						{
							if(!setArg.getSetValues().containsKey(allowed))
							{
								throw new IllegalStateException("Condition on " +
										target + " which is a set argument, " +
										"refers to a value the set cannot take");
							}
						}
					}
				}
			}
		}	
		
		return nodeNames;
	}
	
	private IImmutableSet<String> validateModelAndGetRoots()
	{
		Set<String> nodeNames = validateConditions();

		HashSet<String> foundChildren = new HashSet<String>();
		for(IBasicArgumentInfo basicArg : arguments)
		{
		    if(nodeNames.contains(basicArg.getName()))
		    {
		        throw new IllegalArgumentException("IO Nodes may not share names with arguments");
		    }
		    
			AbstractArgumentInfo arg = (AbstractArgumentInfo)basicArg;
			for(String child : arg.getChildren())
			{
				if(!argumentMap.containsKey(child))
				{
					throw new IllegalStateException("Arguments not in a tree! " +
							"eg. " + child + " is listed as a child of " + 
							arg.getName() + " but isn't in the argument list");
				}
				
				if(foundChildren.contains(child))
				{
					throw new IllegalStateException("Arguments not in a tree! " +
							"eg. " + child + " is the child of at least two" +
							" other arguments! Including " + arg.getName());
				}
				
				foundChildren.add(child);
			}
		}
		
		HashSet<String> rootArgs = new HashSet<String>();
		for(String argname : argumentMap.keySet())
		{
			if(!foundChildren.contains(argname))
			{
				rootArgs.add(argname);
			}
		}
		
		return new ImmutableHashSet<String>(rootArgs);
	}

	/**
	 * @return Returns the rootArguments.
	 */
	public IImmutableSet<String> getRootArguments() {
		return rootArguments;
	}
	
	public Set<String> getAvailableArguments(
			IArgumentInstance instance)
	{
		if(instance == null)
		{
			throw new IllegalArgumentException("null param");
		}
		
		List<String> available = new ArrayList<String>();
		for(String argName : rootArguments)
		{
			available.add(argName);
		}
		
		Map<String, IBasicArgumentValue> assignments = 
			instance.getAssigmentsMap();
		
		int index = 0;
		while(index < available.size())
		{
			String argName = available.get(index);
			AbstractArgumentInfo arg = (AbstractArgumentInfo)argumentMap.get(argName);
			IBasicArgumentValue assignedValue = assignments.get(argName);
			if(arg.getChildren().size() > 0)
			{
				if(assignedValue instanceof BoolArgumentValue)
				{
					if(!(arg instanceof BoolArgumentInfo))
					{
						throw new IllegalArgumentException(argName +
								" is assigned to a bool value, but this argument" +
								" is not a bool");
					}
					BoolArgumentValue boolValue = (BoolArgumentValue)assignedValue;
					BoolArgumentInfo boolArg = (BoolArgumentInfo)arg;
					
					IImmutableSet<String> children;
					if(boolValue.getValue())
					{
						children = boolArg.getTrueChildren();
					}
					else
					{
						children = boolArg.getFalseChildren();
					}
					
					for(String child : children)
					{
						available.add(child);
					}
				}
				else if(assignedValue instanceof SetArgumentValue &&
				        arg instanceof SetArgumentInfo)
				{
				    SetArgumentValue setValue = (SetArgumentValue)assignedValue;
				    SetArgumentInfo setArg = (SetArgumentInfo)arg;
				    
				    for(String child : 
				        ((SetValue)setArg.getSetValue(setValue.getValue())).getChildren())
				    {
				        available.add(child);
				    }
				}
				        
			}
			
			index++;
		}
		
		return new HashSet<String>(available);
	}
	
	
	public IInputOutputNodeTuple getIOFunction(IArgumentInstance instance)
	{
		if(instance == null)
		{
			throw new IllegalArgumentException("null param");
		}
		
		for(IArgumentStateIOMapping mapping : mappings)
		{
			if(mapping.isMatch(instance))
			{
				return new InputOuputNodeTuple(mapping.getInputs(), mapping.getOutputs());
			}
		}

		return new InputOuputNodeTuple(emptyInputs, emptyOutputs);
	}
	
	public IImmutableSet<IInterfaceClass> getTypeDependancies()
	{
	    return dependancies;
	}
	
	public String toString()
	{
		return toString(0);
	}
	
	public String toString(int depth)
	{
		StringBuilder text = new StringBuilder();
		depth = XMLUtil.putOpenElem(text, "argument-model", depth);
		
		depth = XMLUtil.putOpenElem(text, "arguments", depth);
		
		for(AbstractArgumentInfo argument : arguments)
		{
			text.append(argument.toString(depth));
		}
		
		depth = XMLUtil.putCloseElem(text, "arguments", depth);
		

		depth = XMLUtil.putOpenElem(text, "mappings", depth);
		
		for(ArgumentStateIOMapping mapping : mappings)
		{
			text.append(mapping.toString(depth));
		}
		
		depth = XMLUtil.putCloseElem(text, "mappings", depth);
		
		depth = XMLUtil.putCloseElem(text, "argument-model", depth);
		
	    return text.toString();
	}
}
