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

import java.util.Vector;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

import de.ugoe.cs.swe.memos.SettingsManager;
import de.ugoe.cs.swe.memos.Utils;
import de.ugoe.cs.swe.memos.database.DBSearcher;
import de.ugoe.cs.swe.memos.datamodel.Memo;
import de.ugoe.cs.swe.memos.gui.dialogs.SettingsDialog;
import de.ugoe.cs.swe.memos.gui.menu.exportHandler;
import de.ugoe.cs.swe.memos.gui.menu.importHandler;
import de.ugoe.cs.swe.memos.gui.menu.printHandler;
import de.ugoe.cs.swe.memos.gui.menu.searchHHandler;
import de.ugoe.cs.swe.memos.gui.menu.updateHandler;

public class View extends ViewPart {
	private Text searchField;
	private CategoryBrowser catBrowser;
	private CTabFolder tabFolder;
	private TabItem emptySearchTab;
	Color originalSearchFieldColor = null;

	public CategoryBrowser getCatBrowser() {
		return catBrowser;
	}

	public void setCatBrowser(CategoryBrowser catBrowser) {
		this.catBrowser = catBrowser;
	}

	public Text getSearchField() {
		return searchField;
	}

	public View() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void createPartControl(Composite parent) {

		// ((CommandContributionItem) ((MenuManager) parent.getShell()
		// .getMenuBar().getItems()[0].getData()).getItems()[1])
		// .getCommand().getCommand().setEnabled(false);

		// Important !!!!!!!!! for disabling menu items !!!!!!!!!!!!!!!!!!!!!

		// Cat
		// deleteCHandler.setEnabled(false);
		// editCHandler.setEnabled(false);

		// Article
		// createHandler.setEnabled(false);
		// deleteHandler.setEnabled(false);
		// editHandler.setEnabled(false);

		// Edit
		// copyHandler.setEnabled(false);
		// cutHandler.setEnabled(false);
		// insertHandler.setEnabled(false);

		// File
		exportHandler.setEnabled(true);
		importHandler.setEnabled(true);
		printHandler.setEnabled(false);

		// Help
		searchHHandler.setEnabled(false);
		updateHandler.setEnabled(false);

		parent.setLayout(createGridLayout(2));

		createSearchBar(parent);

		catBrowser = new CategoryBrowser(parent);

		createTableFolder(parent);
		if (!SettingsManager.getInstance().settingsFileAlreadyExisted)
			new SettingsDialog(parent.getShell()).open();
	}

	private void createSearchBar(Composite parent) {
		Composite searchBar = new Composite(parent, SWT.BORDER);
		searchBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				2, 1));

		searchBar.setLayout(createGridLayout(4));

		Label searchLabel = new Label(searchBar, SWT.NONE);
		searchLabel.setText("Memos suchen:");
		searchLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false,
				false, 1, 1));

		searchField = new Text(searchBar, SWT.BORDER);
		searchField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				true, 1, 1));
		searchField.addKeyListener(new KeyAdapter() {
			boolean doit = true;

			public void keyPressed(KeyEvent e) {
				if (e.keyCode == SWT.CR) {
					startSearch(true);
					// only search once
					doit = false;
				}
			}

			public void keyReleased(KeyEvent e) {
				if (doit == true) {
					startSearch(false);
				}
				doit = true;
			}
		});
		searchField
				.setToolTipText("geben Sie ihren Suchtext hier ein und starten Sie die Suche durch \"Enter\" oder durch einen Klick auf den Suchbutton");

		originalSearchFieldColor = searchField.getBackground();

		Button searchButton = new Button(searchBar, SWT.NONE);
		searchButton.setText("\u23CE");
		searchButton
				.setToolTipText("Startet die Suche mit der aktuellen Eingabe");
		searchButton.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				startSearch(true);
			}
		});

		Button addButton = new Button(searchBar, SWT.NONE);
		addButton.setText("+");
		addButton
				.setToolTipText("Öffnet ein neues Tab mit der Eingabemaske für einen neuen Artikel");
		addButton.addListener(SWT.Selection, new Listener() {
			public void handleEvent(Event e) {
				CTabItem memoTab = addTabItem("Neu");
				SetTabItemActive(memoTab);
				ArticleComposite articleComposite = new ArticleComposite(
						getTabFolder(), SWT.NONE, null, catBrowser,
						ArticleComposite.MODE.WRITE);
				articleComposite.setContent(searchField.getText());
				articleComposite.setLayout(Utils.createGridLayout(1, 0, 0, 0));
				catBrowser.getTreeMouseListener().setActiveCategoryField(
						articleComposite.getCategoryField());
				memoTab.setControl(articleComposite);
				// memoTab.addDisposeListener(new
				// DisposeArticleListene(Utils.getMainView().getTabFolder()));
			}
		});
	}

	private void startSearch(boolean newTab) {
		DBSearcher dbSearch = new DBSearcher(searchField.getText());

		CTabItem item;

		if (newTab)
			item = addTabItem("S:" + searchField.getText());
		else {
			item = tabFolder.getItem(0);
			item.setText("S:" + searchField.getText());
		}

		SearchResultComposite sRC = new SearchResultComposite(getTabFolder(),
				SWT.NONE, this.catBrowser);
		item.setControl(sRC);
		item.setData(sRC);
		Vector<Memo> result = dbSearch.execute();
		if (result != null) {
			sRC.addResults(result);
			searchField.setBackground(originalSearchFieldColor);

		} else {
			org.eclipse.swt.graphics.Color C = new org.eclipse.swt.graphics.Color(
					getActiveComposite().getDisplay(), new RGB(255, 150, 150));
			searchField.setBackground(C);
		}
		SetTabItemActive(item);
	}

	private void createTableFolder(Composite parent) {
		tabFolder = new CTabFolder(parent, SWT.BORDER);

		tabFolder.addListener(SWT.Selection, new Listener() {

			public void handleEvent(Event event) {

				CTabItem item = (CTabItem) event.item;

				if (item.getData() instanceof SearchResultComposite) {
					SearchResultComposite c = (SearchResultComposite) (item
							.getData());

					c.layout();
				}

			}

		});

		tabFolder.addMouseListener(new MouseListener() {

			@Override
			public void mouseDoubleClick(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseDown(MouseEvent e) {
				try {
					catBrowser.getTreeMouseListener().setActiveCategoryField(
							(((ArticleComposite) ((TabFolder) e.widget)
									.getSelection()[0].getControl())
									.getCategoryField()));
				} catch (Exception e1) {
					// stay still and do nothing...
				}

			}

			@Override
			public void mouseUp(MouseEvent e) {
			}

		});
		startTab();

		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
	}

	private void startTab() {
		Composite startComposite = new Composite(tabFolder, SWT.NONE);
		startComposite.setLayout(new FillLayout());
		Label infoLable = new Label(startComposite, SWT.NONE);
		infoLable.setText("Willkommen bei Memos!\n"
				+ "Dieses Fenster dient als Suchvorschau für Memos");
		CTabItem startTab = addTabItem("Suchvorschau");
		startTab.setShowClose(false);
		SetTabItemActive(startTab);
		startTab.setToolTipText("Startbildschirm");
		startTab.setControl(startComposite);

		// SetTabItemActive(startTab);
	}

	public CTabItem addTabItem(String name) {
		CTabItem tabItem = new CTabItem(tabFolder, SWT.CLOSE);
		tabItem.setText(name);
		tabFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
			public void close(CTabFolderEvent e) {
				if (e.item instanceof ArticleComposite)
					((ArticleComposite) e.item).closeMemo();
			}
		});

		return tabItem;
	}

	public CTabFolder getTabFolder() {
		return tabFolder;
	}

	@Override
	public void setFocus() {
	}

	private GridLayout createGridLayout(int numColumns) {
		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = numColumns;
		return gridLayout;
	}

	public void setEmptySearchTab(TabItem emptySearchTab) {
		this.emptySearchTab = emptySearchTab;
	}

	public TabItem getEmptySearchTab() {
		return emptySearchTab;
	}

	public void SetTabItemActive(CTabItem item) {
		tabFolder.setSelection(item);
	}

	public Composite getActiveComposite() {
		if (tabFolder.getSelection() != null)
			return (Composite) tabFolder.getSelection().getData();
		return null;
	}

	public CategoryBrowser getCategoryBrowser() {
		return this.catBrowser;
	}

	public void closeActiveTabItem() {
		if (tabFolder.getSelection() != null)
			tabFolder.getSelection().dispose();
	}

}
