package bk;

import java.util.ArrayList;
import java.util.List;

import javax.swing.JTree;

import animation.AlgorithmStage;
import animation.CodeLine;
import animation.ControlFlow;
import animation.Memory;
import animation.PseudoCodeNode;
import animation.Memory.MemoryType;
import animation.Memory.ReadOnlyMemory;
import bk.BKNodePlacement.State;
import bk.LayoutType;
import codelines.DeclareVariable;
import codelines.ForEachLoop;
import codelines.ForLoop;
import codelines.FunctionCall;
import codelines.FunctionDefinition;
import codelines.IfLoop;
import codelines.Comment;
import codelines.SetVariable;
import codelines.WhileLoop;
import graph.LayeredGraphEdge;
import graph.LayeredGraphNode;
import lib.TextLayoutHelper;

/**
 * the preprocessing stage of the bk node placement algorithm
 * 
 * @author kolja and eren
 *
 */
public class ConflictDetection implements AlgorithmStage {

    private BKNodePlacement alg;
    
    public ConflictDetection( BKNodePlacement bknpa )
    {
        alg = bknpa;
    }
    
    @Override
    public PseudoCodeNode createPseudocodeTree(JTree tree) {
        String vars[] = { "i", "L", "k0", "l", "l1", "k1", "v", "graph", "n" };
        String params[] = { "graph" };
        @SuppressWarnings("serial")
        PseudoCodeNode root = new PseudoCodeNode(TextLayoutHelper.setupPseudoCode("function mark_conflicts( graph )", vars), tree, new FunctionDefinition( params ) ) {
            @Override
            public String getDebugOutput( Memory m )
            {
                alg.setAlgorithmState( State.CONFLICTS );
                if( m.isSomewhereDefined( "l", MemoryType.LOCAL ) && m.isSomewhereDefined( "i", MemoryType.LOCAL ) && 
                        m.<Integer>read( "l", MemoryType.LOCAL ) < m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1 ).size() )
                    m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.<Integer>read( "i", MemoryType.LOCAL ) + 1).get(m.<Integer>read( "l", MemoryType.LOCAL )).setSelected(null);
                
                if( m.isSomewhereDefined( "i", MemoryType.LOCAL ) && m.isSomewhereDefined( "l1", MemoryType.LOCAL ) &&
                        m.<Integer>read( "l1", MemoryType.LOCAL ) < m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.<Integer>read( "i", MemoryType.LOCAL ) + 1).size() ) {
                    m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.<Integer>read( "i", MemoryType.LOCAL ) + 1).get(m.<Integer>read( "l1", MemoryType.LOCAL )).setSelected(null);
                }
                
                if( m.isSomewhereDefined( "i", MemoryType.LOCAL ) && m.isSomewhereDefined( "k0", MemoryType.LOCAL ) && 
                        m.<Integer>read( "k0", MemoryType.LOCAL ) <  m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.read( "i", MemoryType.LOCAL )).size()) {
                    m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.read( "i", MemoryType.LOCAL )).get(m.<Integer>read( "k0", MemoryType.LOCAL )).setSelected(null);
                }
                
                if( m.isSomewhereDefined( "i", MemoryType.LOCAL ) && m.isSomewhereDefined( "k1", MemoryType.LOCAL ) && 
                        m.<Integer>read( "k1", MemoryType.LOCAL ) < m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.read( "i", MemoryType.LOCAL )).size() ) {
                    m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL).getContainedLayers().get(m.read( "i", MemoryType.LOCAL )).get(m.<Integer>read( "k1", MemoryType.LOCAL )).setSelected(null);
                }
                
                if( m.isSomewhereDefined( "n", MemoryType.LOCAL ) )
                {
                    m.<LayeredGraphNode>read( "n", MemoryType.LOCAL ).setSelected( null );
                }
                String info = "| i  | l  | l1 | k0 | k1 |  v  |  n  |\n";
                info +=       "|----|----|----|----|----|-----|-----|\n";
                String i = "null";
                String l = "null";
                String l1 = "null";
                String k0 = "null";
                String k1 = "null";
                String v = "null";
                String n = "null";
                if( m.isSomewhereDefined( "i", MemoryType.LOCAL ) )
                    i = "" + m.<Integer>read( "i", MemoryType.LOCAL );
                if( m.isSomewhereDefined( "l", MemoryType.LOCAL ) )
                    l = "" + m.<Integer>read( "l", MemoryType.LOCAL );
                if( m.isSomewhereDefined( "l1", MemoryType.LOCAL ) )
                    l1 = "" + m.<Integer>read( "l1", MemoryType.LOCAL );
                if( m.isSomewhereDefined( "k0", MemoryType.LOCAL ) )
                    k0 = "" + m.<Integer>read( "k0", MemoryType.LOCAL );
                if( m.isSomewhereDefined( "k1", MemoryType.LOCAL ) )
                    k1 = "" + m.<Integer>read( "k1", MemoryType.LOCAL );
                if( m.isSomewhereDefined( "v", MemoryType.LOCAL ) && m.<LayeredGraphEdge>read( "v", MemoryType.LOCAL ).getSources().get( 0 ).getName() != null )
                    v = "" + m.<LayeredGraphEdge>read( "v", MemoryType.LOCAL ).getSources().get( 0 ).getName();
                if( m.isSomewhereDefined( "n", MemoryType.LOCAL ) && m.<LayeredGraphNode>read( "n", MemoryType.LOCAL ).getName() != null )
                    n = "" + m.<LayeredGraphNode>read( "n", MemoryType.LOCAL ).getName();
                info += "|" + TextLayoutHelper.strToLen( i, 4 ) + 
                        "|" + TextLayoutHelper.strToLen( l, 4 ) + 
                        "|" + TextLayoutHelper.strToLen( l1, 4 ) + 
                        "|" + TextLayoutHelper.strToLen( k0, 4 ) + 
                        "|" + TextLayoutHelper.strToLen( k1, 4 ) + 
                        "|" + TextLayoutHelper.strToLen( v, 5 ) + 
                        "|" + TextLayoutHelper.strToLen( n, 5 ) + "|\n";
                return info;
            }
        };
        PseudoCodeNode text = new PseudoCodeNode(TextLayoutHelper.setupPseudoCodeStage( "-- mark conflicts in subgraphs --" ), tree, new Comment() );
        root.add( text );
        PseudoCodeNode foreach = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "foreach n in graph.getContainedNodes() do", vars ), tree, new ForEachLoop<LayeredGraphNode>( "n" ) {
			@Override
			protected List<LayeredGraphNode> list(ReadOnlyMemory m) {
				return m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedNodes();
			}
        } );
        root.add( foreach );
        PseudoCodeNode ifNode = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "if n has subgraph then", vars ), tree, new IfLoop() {
			@Override
			protected boolean condition(ReadOnlyMemory m) {
				return m.<LayeredGraphNode>read( "n", MemoryType.LOCAL ).getContainedLayers().size() > 0;
			}
        } );
        foreach.add( ifNode );
        PseudoCodeNode call = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "call mark_conflicts( n );", vars ), tree, new FunctionCall( root, new String[]{ "n" } ) );
        ifNode.add( call );
        text = new PseudoCodeNode(TextLayoutHelper.setupPseudoCodeStage( "-- mark conflicts in graph --" ), tree, new Comment() );
        root.add( text );
        PseudoCodeNode init = new PseudoCodeNode(TextLayoutHelper.setupPseudoCode( "L = graph.getContainedLayers();", vars), tree, new DeclareVariable<ArrayList<ArrayList<LayeredGraphNode>>>( "L" ) {
            @Override
            protected ArrayList<ArrayList<LayeredGraphNode>> value(ReadOnlyMemory m) {
                return m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers();
            }
        } );
        root.add( init );
        PseudoCodeNode outerLoop = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "for i=1 to |L|-2 do", vars ), tree, new ForLoop( "i" ) {
			@Override
			protected int minimum( ReadOnlyMemory m ) {
				return 1;
			}
			@Override
			protected int maximum( ReadOnlyMemory m ) {
				return m.<ArrayList<ArrayList<LayeredGraphNode>>>read( "L", MemoryType.LOCAL ).size() - 2;
			}
        } );
        root.add( outerLoop );
        PseudoCodeNode line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "k0 = 0; l = 0;", vars ), tree, new CodeLine() {
			@Override
			public ControlFlow runForward(Memory m) {
				m.declare( "k0", 0, MemoryType.LOCAL );
				m.declare( "l", 0, MemoryType.LOCAL );
				actions.push( (Memory mem) -> {
					mem.undeclare( "k0", MemoryType.LOCAL );
					mem.undeclare( "l", MemoryType.LOCAL );
				} );
				return new ControlFlow( ControlFlow.STEP_OVER );
			}
        } );
        outerLoop.add( line );
        PseudoCodeNode innerLoop = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "for l1=0 to |L[i+1]|-1 do", vars ), tree, new ForLoop( "l1" ) {
			@Override
			protected int minimum(ReadOnlyMemory m) {
				return 0;
			}
			@Override
			protected int maximum(ReadOnlyMemory m) {
				return m.<ArrayList<ArrayList<LayeredGraphNode>>>read( "L", MemoryType.LOCAL ).get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1 ).size() - 1;
			}
        } );
        outerLoop.add( innerLoop );
        ifNode = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "if l1==|L[i+1]|-1 or L[i+1][l1] incident to inner segment between L[i+1] and L[i] then", vars ), tree, new IfLoop() {
			@Override
			protected boolean condition(ReadOnlyMemory m) {
	            return m.<Integer>read( "l1", MemoryType.LOCAL ) == m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1).size() - 1 || 
	            		incidentToInnerSegmentBetweenLiPlusOneAndLi( m );
			}
        } );
        innerLoop.add( ifNode );
        line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "k1 = |L[i]|-1;", vars ), tree, new DeclareVariable<Integer>( "k1" ) {
			@Override
			protected Integer value(ReadOnlyMemory m) {
				return (int)m.<ArrayList<ArrayList<LayeredGraphNode>>>read( "L", MemoryType.LOCAL ).get( m.read( "i", MemoryType.LOCAL ) ).size() - 1;
			}
        } );
        ifNode.add( line );
        PseudoCodeNode innerIfNode = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "if L[i+1][l1] incident to inner segment between L[i+1] and L[i] then", vars ), tree, new IfLoop() {
			@Override
			protected boolean condition(ReadOnlyMemory m) {
				return incidentToInnerSegmentBetweenLiPlusOneAndLi( m );
			}
		} );
        ifNode.add( innerIfNode );
        
        line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "k1 = pos(pred(L[i+1][l1])[0]);", vars ), tree, new SetVariable<Integer>( "k1" ) {
			@Override
			protected Integer value(ReadOnlyMemory m) {
				return (int)m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.read( "i", MemoryType.LOCAL ) ).indexOf(
						m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1 ).get( m.read( "l1", MemoryType.LOCAL ) ).getSortedIncomingEdges().get( 0 ).getSources().get( 0 ) );
			}
        } );
        innerIfNode.add( line );
        PseudoCodeNode whileLoop = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "while l <= l1 do", vars ), tree, new WhileLoop() {
			@Override
			protected boolean condition( ReadOnlyMemory m ) {
				return m.<Integer>read( "l", MemoryType.LOCAL ) <= m.<Integer>read( "l1", MemoryType.LOCAL );
			}
        } );
        ifNode.add( whileLoop );
        foreach = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "foreach v in pred(L[i+1][l]) do", vars ), tree, new ForEachLoop<LayeredGraphEdge>( "v" ) {
			@Override
			protected List<LayeredGraphEdge> list(ReadOnlyMemory m) {
				return m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1 ).get( m.read( "l", MemoryType.LOCAL ) ).getIncomingEdges();
			}
        } );
        whileLoop.add( foreach );
        innerIfNode = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "if pos(v) < k0 or pos(v) > k1 then", vars ), tree, new IfLoop() {
			@Override
			protected boolean condition(ReadOnlyMemory m) {
			    int k = m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.read( "i", MemoryType.LOCAL ) ).indexOf( m.<LayeredGraphEdge>read( "v", MemoryType.LOCAL ).getSources().get( 0 ) );
				return k < m.<Integer>read( "k0", MemoryType.LOCAL ) || k > m.<Integer>read( "k1", MemoryType.LOCAL );
			}
        } );
        foreach.add( innerIfNode );
        line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "mark segment (v,L[i+1][l]);", vars ), tree, new CodeLine() {
			@Override
			public ControlFlow runForward(Memory m) {
				LayeredGraphEdge e = m.read( "v", MemoryType.LOCAL );
				boolean old = e.isConflicted( LayoutType.TOP_BOTTOM_LEFT );
				e.setConflicted( true, null );
				actions.add( (Memory mem) -> {
					e.setConflicted( old, null );
				});
				return new ControlFlow( ControlFlow.STEP_OVER );
			}
        } );
        innerIfNode.add( line );
        line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "l = l+1;", vars ), tree, new SetVariable<Integer>( "l" ) {
			@Override
			protected Integer value(ReadOnlyMemory m) {
				return (int)m.<Integer>read( "l", MemoryType.LOCAL ) + 1;
			}
        } );
        whileLoop.add( line );
        line = new PseudoCodeNode( TextLayoutHelper.setupPseudoCode( "k0 = k1;", vars ), tree, new SetVariable<Integer>( "k0" ) {
			@Override
			protected Integer value(ReadOnlyMemory m) {
				return (int)m.<Integer>read( "k1", MemoryType.LOCAL );
			}
        } );
        ifNode.add( line );
        return root;
    }
    
    private boolean incidentToInnerSegmentBetweenLiPlusOneAndLi( ReadOnlyMemory m ) {
        LayeredGraphNode curr = m.<LayeredGraphNode>read( "graph", MemoryType.LOCAL ).getContainedLayers().get( m.<Integer>read( "i", MemoryType.LOCAL ) + 1 ).get( m.read( "l1", MemoryType.LOCAL ) );
        for (LayeredGraphEdge e : curr.getIncomingEdges()) {
            if (e.isDummyEdge()) {
                return true;
            }
        }
        return false;
    }
}
