package org.maltparser.parser.algorithm.planar3T;


import java.util.Set;
import java.util.Stack;

import org.maltparser.core.exception.MaltChainedException;
import org.maltparser.core.syntaxgraph.DependencyStructure;
import org.maltparser.core.syntaxgraph.edge.Edge;
import org.maltparser.core.syntaxgraph.node.DependencyNode;
import org.maltparser.core.syntaxgraph.node.TokenNode;
import org.maltparser.parser.ParserConfiguration;
import org.maltparser.parser.TransitionSystem;
import org.maltparser.parser.algorithm.planar.PlanarConfig;
import org.maltparser.parser.history.GuideUserHistory;
import org.maltparser.parser.history.History;
import org.maltparser.parser.history.action.ComplexDecisionAction;
import org.maltparser.parser.history.action.GuideUserAction;
import org.maltparser.parser.transition.TransitionTable;

public class Planar3T extends TransitionSystem {
	protected static final int SHIFT = 1;
	protected static final int REDUCE = 2;
	protected static final int ARC = 3;
	//protected static final int RIGHTARC = 3;
	//protected static final int LEFTARC = 4;
	
	public Planar3T() throws MaltChainedException {
		super();
	}
	
	public void apply(GuideUserAction currentAction, ParserConfiguration config) throws MaltChainedException {
		Planar3TConfig planarConfig = (Planar3TConfig)config;
		Stack<DependencyNode> stack = planarConfig.getStack();
		Stack<DependencyNode> input = planarConfig.getInput();
		currentAction.getAction(actionContainers);
		Edge e = null;
		switch (transActionContainer.getActionCode()) {
		case ARC:
			e = planarConfig.getDependencyStructure().addDependencyEdge(stack.peek().getIndex(), input.peek().getIndex());
			addEdgeLabels(e);
			break;
		case REDUCE:
			stack.pop();
			break;
		default: //SHIFT
			stack.push(input.pop()); 
			break;
		}
	}
	
	public GuideUserAction getDeterministicAction(GuideUserHistory history, ParserConfiguration config) throws MaltChainedException {
		Planar3TConfig planar3TConfig = (Planar3TConfig)config;
		if (planar3TConfig.getRootHandling() != Planar3TConfig.NORMAL && planar3TConfig.getStack().peek().isRoot()) {
			return updateActionContainers(history, Planar3T.SHIFT, null);
		}
		//TODO: yeah, shift root
		return null;
	}
	
	protected void addAvailableTransitionToTable(TransitionTable ttable) throws MaltChainedException {
		ttable.addTransition(SHIFT, "SH", false, null);
		ttable.addTransition(REDUCE, "RE", false, null);
		//ttable.addTransition(RIGHTARC, "RA", true, null);
		//ttable.addTransition(LEFTARC, "LA", true, null);
		ttable.addTransition(ARC, "AR", true, null);
    }
	
	protected void initWithDefaultTransitions(GuideUserHistory history) throws MaltChainedException {
		GuideUserAction currentAction = new ComplexDecisionAction((History)history);
		
		transActionContainer.setAction(SHIFT);
		transActionContainer.setAction(REDUCE);
		for (int i = 0; i < arcLabelActionContainers.length; i++) {
			arcLabelActionContainers[i].setAction(-1);
		}
		currentAction.addAction(actionContainers);
	}
	
	public String getName() {
		return "planar 3t arc-eager";
	}

	public boolean permissible(GuideUserAction currentAction, ParserConfiguration config) throws MaltChainedException {
		currentAction.getAction(actionContainers);
		int trans = transActionContainer.getActionCode();
		Planar3TConfig planarConfig = (Planar3TConfig)config;
		DependencyNode stackPeek = planarConfig.getStack().peek();
		DependencyNode inputPeek = planarConfig.getInput().peek();
		DependencyStructure dg = planarConfig.getDependencyGraph();
		int rootHandling = planarConfig.getRootHandling();
		boolean singleHeadConstraint = planarConfig.requiresSingleHead();
		boolean noCoveredRootsConstraint = planarConfig.requiresNoCoveredRoots();
		boolean acyclicityConstraint = planarConfig.requiresAcyclicity();
		boolean connectednessConstraintOnReduce = planarConfig.requiresConnectednessCheckOnReduce();
		boolean connectednessConstraintOnShift = planarConfig.requiresConnectednessCheckOnShift();
		if ((trans == ARC) && !isActionContainersLabeled()) {
			return false;
		}
		
		if (trans == ARC) {
			if(checkIfNodesAreRelated( dg ,  inputPeek.getIndex() , stackPeek.getIndex() ) )
			{	
				return false;
			}
			if ( acyclicityConstraint && stackPeek.findComponent().getIndex() == inputPeek.findComponent().getIndex() )
			{	
				return false;
			}
		}
		
		
		
		if (trans == REDUCE) {
			//do not reduce the dummy root
			if ( stackPeek.isRoot() ) 
				return false;
			//enforce no-covered-roots constraint if present
			if ( !stackPeek.hasHead() && noCoveredRootsConstraint )
				return false;
			//TODO does this line still make sense? (from Nivre arc-eager)
			//if ( !stackPeek.hasHead() && rootHandling == PlanarConfig.STRICT ) 
			//	return false;
			//enforce connectedness constraint if present
			if ( connectednessConstraintOnReduce )
			{
				boolean path1 = ( stackPeek.findComponent().getIndex() == inputPeek.findComponent().getIndex() );
				boolean path2;
				if ( planarConfig.getStack().size() < 2 ) path2=false;
				else
				{
					DependencyNode stackPrev = planarConfig.getStack().get(planarConfig.getStack().size()-2);
					path2 = stackPrev.findComponent().getIndex() == stackPeek.findComponent().getIndex();
				}
				return path1 || path2;
			}
		}
		if (trans == REDUCE && !stackPeek.hasHead() && rootHandling == Planar3TConfig.STRICT) {
			return false;
		}
		if ( trans == SHIFT )
		{
			if ( connectednessConstraintOnShift && planarConfig.getInput().size() == 1 ) //last word
			{
				boolean path = ( planarConfig.getDependencyGraph().getTokenNode(1).findComponent().getIndex() == inputPeek.findComponent().getIndex() ); //require connection to 1st
				return path;
			}
		}
		return true;
	}
	
	public GuideUserAction defaultAction(GuideUserHistory history, ParserConfiguration configuration) throws MaltChainedException {
		return updateActionContainers(history, Planar3T.SHIFT, null);
	}
	
	private boolean checkIfNodesAreRelated( DependencyStructure dg , int index1 , int index2 ) throws MaltChainedException
	{
		TokenNode tk=dg.getTokenNode(index1);
		Set<DependencyNode> heads=null;
		if(tk!=null){
		   heads=tk.getHeads();
		
		   for (DependencyNode head : heads) {
			if(head.getIndex()==index2)
			{
				return true;
			}
		   }
		}   
		
		tk=dg.getTokenNode(index2);
		if(tk!=null){
		   heads=tk.getHeads();
		   for (DependencyNode head : heads) {
			if(head.getIndex()==index1)
			{
				return true;
			}
		  }
		}   
		return false;
	}
}