package de.ugoe.cs.swe.memos.gui.mainview;

import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.ui.PlatformUI;

import de.ugoe.cs.swe.memos.Utils;
import de.ugoe.cs.swe.memos.datamodel.Category;
import de.ugoe.cs.swe.memos.datamodel.Memo;
import de.ugoe.cs.swe.memos.gui.menu.deleteCHandler;
import de.ugoe.cs.swe.memos.gui.menu.editCHandler;
import de.ugoe.cs.swe.memos.gui.menu.importHandler;

public class TreeMouseListener extends MouseAdapter {

	private Text category;
	private CategoryBrowser cbrowser;
	private Category selectedCategory = null;
		
	public TreeMouseListener(CategoryBrowser cbrowser) {
		this.cbrowser = cbrowser;
	}

	public void mouseDoubleClick(MouseEvent e) {
		
		importHandler.setEnabled(true);
		
		PlatformUI.getWorkbench().getDisplay().update()  ;
		
		
		
		Tree tree = (Tree) e.widget;
		TreeItem selectedItem = tree.getSelection()[0];
		if (selectedItem != null) {
			// TODO: ADD Code that opens a new tab wich displays all Memos that
			// are marked with the doubleclicked Category
			Category c = (Category)selectedItem.getData();
			CTabItem item = Utils.getMainView().addTabItem("K:" + c.getName());
			Utils.getMainView().SetTabItemActive(item);
			SearchResultComposite sRC = new SearchResultComposite(Utils.getMainView().getTabFolder(), SWT.NONE, cbrowser);
			
			item.setControl(sRC);
			item.setData(sRC);
			c.loadMemosFromDB();
			sRC.addResults(new Vector<Memo>(c.getMemos()));
			

		}

	}
	
	public void mouseDown(MouseEvent e) {
	}

	public void mouseUp(MouseEvent e) {
		if (cbrowser.getCategoryTree().getItem(new Point(e.x, e.y)) == null) {
			cbrowser.getCategoryTree().deselectAll();
			try {
			this.category.setText("");
			}
			catch (Exception e1) {
				// TODO fix this really
			}
			deleteCHandler.setEnabled(true);
			editCHandler.setEnabled(true);
		}
		
		this.updateSelectedCategory();
		
	}
	
	public Category getSelectedCategory() {
		return selectedCategory;
	}

	public void setSelectedCategory(Category selectedCategory) {
		this.selectedCategory = selectedCategory;
	}

	public void setActiveCategoryField(Text activeCategoryField) {
		this.category = activeCategoryField;
	}
	
	public void updateSelectedCategory() {
		this.selectedCategory = cbrowser.getSelectedCategory();
		if (this.selectedCategory != null && this.category != null){
			this.category.setText(this.selectedCategory.getName());
			this.category.setData(selectedCategory);
		}
	}
	
//	private findAllExpandedTreeItems(TreeItem item, ArrayList<TreeItem> results) {
//		
//	}

};
