/*******************************************************************************
* 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 20.10.2004
 *
 */

package uk.ac.ic.doc.kevlar.gui.internal.taskpane.programpane;

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

import org.eclipse.swt.graphics.Point;

import uk.ac.ic.doc.kevlar.gui.GUIManager;
import uk.ac.ic.doc.kevlar.gui.internal.animation.AAnimation;
import uk.ac.ic.doc.kevlar.gui.internal.animation.AnimationGroupListenerEntry;
import uk.ac.ic.doc.kevlar.gui.internal.animation.AnimationManager;
import uk.ac.ic.doc.kevlar.gui.internal.animation.IAnimationListener;
import uk.ac.ic.doc.kevlar.gui.internal.dragdrop.ADraggableObject;
import uk.ac.ic.doc.kevlar.gui.internal.taskpane.AScrollingTaskPane;
import uk.ac.ic.doc.kevlar.hial.IHialEventListener;
import uk.ac.ic.doc.kevlar.hial.IProgramCategoryNode;
import uk.ac.ic.doc.kevlar.hial.IProgramNode;
import uk.ac.ic.doc.kevlar.hial.IProgramTreeNode;
import uk.ac.ic.doc.kevlar.publicUtil.collections.IImmutableList;

/**
 * @author ei02
 *
 */
public class ProgramPane extends AScrollingTaskPane implements IAnimationListener, IHialEventListener {

    protected List<AProgramTreeNodeEntry> entries;
    protected int selected;
    protected IProgramCategoryNode current;
	
	public ProgramPane(Point position){
	    
		super(position);
		
		scrollbar.setIncrement(15);
		entries = new ArrayList<AProgramTreeNodeEntry>();
		refresh((IProgramCategoryNode)GUIManager.getHial().getProgramTreeRoot().getFirst());
		
		setSelected(-1);
		GUIManager.getHial().setGUIListener(this);
		
	}
	
	public void setSelected(int index) {
	    
	    if (selected >= 0 && selected < entries.size()) {
	        
	        entries.get(selected).deselect();
	        
	    }

	    if (index >= -1 && index < entries.size()) {
	        
	        selected = index;
	        
	    }
	    
	    if (selected >= 0) {
	        
	        AProgramTreeNodeEntry selectedEntry = entries.get(selected);
	        selectedEntry.select();
	        scrollTo(selectedEntry);
	        
	    } else {
	        
	        scrollTo(0);
	        
	    }
	    
	}
	
	public AProgramTreeNodeEntry getSelected() {
	    
	    if (selected >= 0 && selected < entries.size()) {
	        
	        return entries.get(selected);
	        
	    } else {
	        
	        return null;
	        
	    }
	    
	}
	
	public int moveUp() {
	    
	    if (selected >= 0 && selected < entries.size()) {
	        
	        entries.get(selected).deselect();
	        
	    }
	    
	    selected--;
	    
	    if (selected < 0) {
	        
	        selected = entries.size()-1;
	        
	    }
	    
	    if (selected >= 0) {
	        
	        AProgramTreeNodeEntry selectedEntry = entries.get(selected);
	        selectedEntry.select();
	        scrollTo(selectedEntry);
	        
	    }
	    
	    return selected;
	    
	}
	
	public int moveDown() {
	    
	    if (selected >= 0 && selected < entries.size()) {
	        
	        entries.get(selected).deselect();
	        
	    }
	    
	    selected++;
	    
	    if (selected >= entries.size()) {
	        
	        selected = 0;
	        
	    }
	    
	    if (selected >= 0) {
	        
	        AProgramTreeNodeEntry selectedEntry = entries.get(selected);
	        selectedEntry.select();
	        scrollTo(selectedEntry);
	        
	    }
	    
	    return selected;
	    
	}
	
	public void select() {
	    
	    AProgramTreeNodeEntry selectedEntry = getSelected();
	    
	    if (selectedEntry != null) {

	        selectedEntry.perform();
	        
	    }
	    
	}
		
	public String getName() {
	    
	    return "Programs";
	    
	}

	public void refresh() {
	    
	    refresh(current, AProgramTreeNodeEntry.SLIDE_LEFT);
	    
	}
	
	public void refresh(IProgramCategoryNode node) {
	    
	    refresh(node, AProgramTreeNodeEntry.NO_ANIMATION);
	    
	}
	
	public void refresh(IProgramCategoryNode node, int animationMode) {
	    
//		entries.clear();
//	    removeAllChildren();
	    
	    current = node;
	    
	    int i = 0;
	    while (i < entries.size()) {
	        
	        AProgramTreeNodeEntry entry = entries.get(i);
	        
	        if (!isParentOf(entry.getDataNode(), node) && !isImmediateChildOf(entry.getDataNode(), node)) {
	        
	            entry.dispose(animationMode);
	            entries.remove(i);
	            
	        } else {
	            
	            i++;
	            
	        }
	        
	    }
	    
		int positionIndex = 0;
		ArrayList<AAnimation> anims = new ArrayList<AAnimation>();
		
		//populate pane with parents entries
		
		LinkedList<IProgramCategoryNode> parents = new LinkedList<IProgramCategoryNode>();

		IProgramCategoryNode currentParent = node;
		
		while(currentParent!=null)
		{
			parents.add(currentParent);
			currentParent = currentParent.getParent();
		}
		
		while(!parents.isEmpty())
		{
			IProgramCategoryNode parent = parents.getLast();
			AProgramTreeNodeEntry entry = getEntry(parent);
			
			if (entry != null) {

			    if (entry instanceof ChildCategoryEntry) {
			        
			        entries.remove(entry);
			        entry = ((ChildCategoryEntry)entry).convertToParent();
			        entries.add(entry);
			        
			    }
			    
			    anims.add(entry.setIndex(positionIndex));
			    
			} else {
			
			    entry = new ParentCategoryEntry(parent, positionIndex, this, animationMode);
			    entries.add(entry);
			    addChild(entry);
			    
			}
			    
			parents.removeLast();
			positionIndex++;
		}
		
		//populate pane with children categories
		
		IImmutableList childNodes = node.getChildren();
		
		for(i = 0; i<childNodes.size(); i++) {
		    
			IProgramTreeNode child = (IProgramTreeNode) childNodes.get(i);
			
			if (child instanceof IProgramCategoryNode ) {

			    AProgramTreeNodeEntry entry = getEntry(child);
			    
			    if (entry != null) {
			        
			        if (entry instanceof ParentCategoryEntry) {
			            
			            entries.remove(entry);
			            entry = ((ParentCategoryEntry)entry).convertToChild();
			            entries.add(entry);
			            
			        }
			        
			        entry.setIndex(positionIndex);
			        
			    } else {
			    
			        entry = new ChildCategoryEntry((IProgramCategoryNode)child, positionIndex, this, animationMode);
			        entries.add(entry);
			        addChild(entry);
			        
			    }
			        
				positionIndex++;
				
			}
			
		}
		
		//populate pane with program enitries
		
		for (i = 0; i<childNodes.size(); i++) {
		    
			IProgramTreeNode child = (IProgramTreeNode) childNodes.get(i);
			
			if (child instanceof IProgramNode) {

			    AProgramTreeNodeEntry entry = getEntry(child);
			    
			    if (entry != null) {
			        
			        entry.setIndex(positionIndex);
			        
			    } else {
			    
			        entry = new ProgramEntry(child, positionIndex, this, animationMode);
			        entries.add(entry);
			        addChild(entry);
			        
			    }
			    
				positionIndex++;
				
			}
			
		}	

		int temp = entries.indexOf(getEntry(node));
		
		if (temp == -1) {
		
		    setSelected(0);
		    
		} else {
		    
		    setSelected(temp);
		    
		}		

		AnimationManager.getSingleton().addAnimationListener(new AnimationGroupListenerEntry(this, anims));
		contents.update();
		
		redraw();
		applyRedraw();
		
	}
	
	public AProgramTreeNodeEntry getEntry(IProgramTreeNode node) {
	    
	    for (int i=0; i<entries.size(); i++) {
	        
	        AProgramTreeNodeEntry entry = entries.get(i);
	        
	        if (entry.getDataNode() == node) {
	            
	            return entry;
	            
	        }
	        
	    }
	    
	    return null;
	    
	}
	
	public boolean isParentOf(IProgramTreeNode parent, IProgramTreeNode node) {
	    
	    if (node == null) {
	        
	        return false;
	        
	    } else {
	        
	        return (parent == node) || isParentOf(parent, node.getParent());
	        
	    }
	    
	}
	
	public boolean isImmediateChildOf(IProgramTreeNode child, IProgramCategoryNode node) {
	    
	    IImmutableList<IProgramTreeNode> dataChildren = node.getChildren();
	    
	    for (int i=0; i<dataChildren.size(); i++) {
	        
	        IProgramTreeNode c = dataChildren.get(i);
	        
	        if (child == c) {
	            
	            return true;
	            
	        }
	        
	    }
	    
	    return false;
	    
	}
	
/*	public boolean mouseMoving(int x, int y)
	{
		for (int i = 0; i<entries.size(); i++)
		{
			AProgramTreeNodeEntry entry = entries.get(i);
			entry.concreteMouseMove(x,y);
		}
	} */
	
	public void mousePress(int x, int y, int mouseButton) {
		
/*		for (int i = 0; i<children.size(); i++) {
			AProgramTreeNodeEntry entry = (AProgramTreeNodeEntry)children.get(i);
			entry.concreteMouseDown(x, y, mouseButton);
		} */
		
	}
	
	public void mouseRelease(int x, int y, int mouseButton)
	{
		for (int i = 0; i<entries.size(); i++) {
			AProgramTreeNodeEntry entry = entries.get(i);
			entry.concreteMouseUp(x, y, mouseButton);
		}
	}

	public void onDrop(ADraggableObject o,int x, int y){
	    
		redraw();
		applyRedraw();
		
	}	
	
	public void animationFinished() {
	    
	    setSelected(selected);
	    
	}

    public void availableProgramsUpdated() {
        
        refresh((IProgramCategoryNode)GUIManager.getHial().getProgramTreeRoot().getFirst(), AProgramTreeNodeEntry.SLIDE_LEFT);
        
    }
	
}
