/*******************************************************************************
* 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 24-Dec-2004
 *
 */

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

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

import org.eclipse.swt.graphics.Point;

import uk.ac.ic.doc.kevlar.core.framework.internal.execute.ExecutionEngineProvider;
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;

/**
 * @author Kate
 *
 */

public abstract class ADirectoryBrowsePane extends AScrollingTaskPane implements IAnimationListener {

    protected List<ADirectoryTreeNodeEntry> entries;
    protected int directoryTreeOffset;
    protected int selected;
    protected IDirectoryNode root;
	
	public ADirectoryBrowsePane(Point position, int directoryTreeOffset){
	    
		super(position);
		this.directoryTreeOffset = directoryTreeOffset;
		
		scrollbar.setIncrement(15);
		entries = new ArrayList<ADirectoryTreeNodeEntry>();
		root = DirectoryNodeProvider.getRootDirectoryNode(ExecutionEngineProvider.getExecutionEngine().getCurrentWorkingDirectory());
		refresh(root);
		
		//refresh(DirectoryNodeProvider.getRootDirectoryNode(ExecutionEngineProvider.getExecutionEngine().getCurrentWorkingDirectory()));
		
		setSelected(-1);
		
	}
	
	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) {
	        
	        ADirectoryTreeNodeEntry selectedEntry = entries.get(selected);
	        selectedEntry.select();
	        scrollTo(selectedEntry);
	        
	    } else {
	        
	        scrollTo(0);
	        
	    }
	    
	}
	
	public ADirectoryTreeNodeEntry 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) {
	        
	        ADirectoryTreeNodeEntry 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) {
	        
	        ADirectoryTreeNodeEntry selectedEntry = entries.get(selected);
	        selectedEntry.select();
	        scrollTo(selectedEntry);
	        
	    }
	    
	    return selected;
	    
	}
	
	public void select() {
	    
	    ADirectoryTreeNodeEntry selectedEntry = getSelected();
	    
	    if (selectedEntry != null) {

	        selectedEntry.perform();
	        
	    }
	    
	}
	
	public String getName() {
	    
	    return "Directory";
	    
	}
	
	public void refresh(IDirectoryNode node) {
	    
	    refresh(node, ADirectoryTreeNodeEntry.NO_ANIMATION);
	    
	}
	
	public void refresh(IDirectoryNode node, int animationMode) {
	    
	    contents.noUpdates();
	    
	    int i = 0;
	    while (i < entries.size()) {
	        
	        ADirectoryTreeNodeEntry entry = entries.get(i);
	        
	        if (!isParentOf(entry.getDataNode(), node) && !isImmediateChildOf(entry.getDataNode(), node)) {
	        
	            entry.dispose(animationMode);
	            entries.remove(i);
	            
	        } else {
	            
	            i++;
	            
	        }
	        
	    }
	    
		int positionIndex = directoryTreeOffset;
		ArrayList<AAnimation> anims = new ArrayList<AAnimation>();
		
		//populate pane with parents entries
		
		LinkedList<IDirectoryNode> parents = new LinkedList<IDirectoryNode>();

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

			    if (entry instanceof DirectoryEntry) {
			        
			        entries.remove(entry);
			        entry = ((DirectoryEntry)entry).convertToParent();
			        entries.add(entry);
			        
			    }
			    
			    anims.add(entry.setIndex(positionIndex));
			    
			} else {
			
			    entry = new OpenDirectoryEntry(parent, positionIndex, this, animationMode);
			    entries.add(entry);
			    addChild(entry);
			    
			}
			    
			parents.removeLast();
			positionIndex++;
		}
		
		//populate pane with children categories
		
		ArrayList<IDirectoryTreeNode> childNodes = node.getChildren();
		
		for(i = 0; i<childNodes.size(); i++) {
		    
			IDirectoryTreeNode child = childNodes.get(i);
			
			if (child instanceof IDirectoryNode) {

			    ADirectoryTreeNodeEntry entry = getEntry(child);
			    
			    if (entry != null) {
			        
			        if (entry instanceof OpenDirectoryEntry) {
			            
			            entries.remove(entry);
			            entry = ((OpenDirectoryEntry)entry).convertToChild();
			            entries.add(entry);
			            
			        }
			        
			        entry.setIndex(positionIndex);
			        
			    } else {
			    
			        entry = new DirectoryEntry((IDirectoryNode)child, positionIndex, this, animationMode);
			        entries.add(entry);
			        addChild(entry);
			        
			    }
			        
				positionIndex++;
				
			}
			
		}
		
		//populate pane with program enitries
		
		populateWithFiles(positionIndex, childNodes, animationMode);
		
		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 ADirectoryTreeNodeEntry getEntry(IDirectoryTreeNode node) {
	    
	    for (int i=0; i<entries.size(); i++) {
	        
	        ADirectoryTreeNodeEntry entry = entries.get(i);
	        
	        if (entry.getDataNode() == node) {
	            
	            return entry;
	            
	        }
	        
	    }
	    
	    return null;
	    
	}
	
	public boolean isParentOf(IDirectoryTreeNode parent, IDirectoryTreeNode node) {
	    
	    if (node == null || !(parent instanceof IDirectoryNode)) {
	        
	        return false;
	        
	    } else {
	        
	        return (parent == node) || isParentOf(parent, ((IDirectoryNode)node).getParent());
	        
	    }
	    
	}
	
	public boolean isImmediateChildOf(IDirectoryTreeNode child, IDirectoryTreeNode node) {
	    
	    if (child instanceof IDirectoryNode) {
	    
	        ArrayList<IDirectoryTreeNode> dataChildren = ((IDirectoryNode)node).getChildren();
	    
	        for (int i=0; i<dataChildren.size(); i++) {
	        
	            IDirectoryTreeNode c = dataChildren.get(i);
	        
	            if (child == c) {
	            
	                return true;
	            
	            }
	        
	        }
	        
	    }
	    
	    return false;
	    
	}
	
	public void mouseRelease(int x, int y, int mouseButton)
	{
		for (int i = 0; i<entries.size(); i++) {
			ADirectoryTreeNodeEntry 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 abstract void populateWithFiles(int positionIndex, ArrayList childNodes, int animationMode);
	
}
