/*
 * Copyright (c) 2006-2008 Maskat Project.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Maskat Project - initial API and implementation
 */
package org.maskat.ui.views.properties.tabbed.masterdetails;

import org.eclipse.gef.EditDomain;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.Tool;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
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.Text;
import org.eclipse.ui.forms.widgets.ExpandableComposite;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;

import org.maskat.core.event.Target;
import org.maskat.ui.Messages;
import org.maskat.ui.editors.layout.tools.DataBindingTool;
import org.maskat.ui.editors.layout.tools.UndoableDataBindingTool;
import org.maskat.ui.views.properties.tabbed.beanwrapper.TargetNode;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class TargetDetailsPage extends AbstractMaskatDetailsPage implements
		ISimpleCallbackInterface {

	private static final String SECTION_TEXT = Messages
			.getString("targetDetails.sectionText"); //$NON-NLS-1$

	private static final String DESCRIPTION = Messages
			.getString("targetDetails.description"); //$NON-NLS-1$

	private static final String TARGET_TEXT = Messages
			.getString("targetDetails.targetText"); //$NON-NLS-1$

	private static final String TARGET_DESCRIPTION = Messages
			.getString("targetDetails.targetDescription"); //$NON-NLS-1$

	private Text nodeNameText;

	private Text dataTargetNameText;

	private Button customObjectButton;

	private Text dataConsumerFunctionText;

	private Target target;

	private Button selectDataTargetButton;

	protected DataBindingTool tool;

	protected TargetDetailsPage callbackRefrence;

	private GraphicalViewer graphicalViewer;

	public TargetDetailsPage(TreeViewer treeViewer) {
		this.masterBlockTreeViewer = treeViewer;
	}

	public void createContents(Composite parent) {

		callbackRefrence = this;

		TableWrapLayout layout = new TableWrapLayout();
		layout.topMargin = 0;
		layout.leftMargin = 5;
		layout.rightMargin = 5;
		layout.bottomMargin = 5;
		parent.setLayout(layout);

		FormToolkit toolkit = managedForm.getToolkit();

		/**
		 * 
		 */
		Section targetNodeSection = toolkit.createSection(parent,
				ExpandableComposite.TITLE_BAR | Section.DESCRIPTION);
		targetNodeSection.setText(SECTION_TEXT);
		targetNodeSection.setDescription(DESCRIPTION);
		TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL,
				TableWrapData.TOP);
		tableWrapData.grabHorizontal = true;
		targetNodeSection.setLayoutData(tableWrapData);

		Composite sourceNodeComposite = toolkit
				.createComposite(targetNodeSection);
		sourceNodeComposite.setLayout(new GridLayout(3, false));

		toolkit.createLabel(sourceNodeComposite, Messages
				.getString("targetDetails.nodeNameLabel")); //$NON-NLS-1$
		toolkit.createLabel(sourceNodeComposite, ":");
		nodeNameText = toolkit.createText(sourceNodeComposite, "", SWT.SINGLE
				| SWT.BORDER);
		nodeNameText.setLayoutData(new GridData(SWT.FILL, 0, true, false));

		/**
		 * 
		 */
		Section targetObjSection = toolkit.createSection(parent,
				ExpandableComposite.TITLE_BAR | Section.DESCRIPTION);
		targetObjSection.setText(TARGET_TEXT);
		targetObjSection.setDescription(TARGET_DESCRIPTION);
		tableWrapData = new TableWrapData(TableWrapData.FILL, TableWrapData.TOP);
		tableWrapData.grabHorizontal = true;
		targetObjSection.setLayoutData(tableWrapData);

		Composite targetObjComposite = toolkit
				.createComposite(targetObjSection);
		targetObjComposite.setLayout(new GridLayout(4, false));

		toolkit.createLabel(targetObjComposite, Messages
				.getString("targetDetails.dataTargetLabel")); //$NON-NLS-1$
		toolkit.createLabel(targetObjComposite, ":");
		dataTargetNameText = toolkit.createText(targetObjComposite, "",
				SWT.SINGLE | SWT.BORDER);
		dataTargetNameText
				.setLayoutData(new GridData(SWT.FILL, 0, true, false));
		selectDataTargetButton = toolkit
				.createButton(
						targetObjComposite,
						Messages
								.getString("targetDetails.dataTargetButtonLabel"), SWT.PUSH); //$NON-NLS-1$

		toolkit.createLabel(targetObjComposite, Messages
				.getString("targetDetails.customObjLabel")); //$NON-NLS-1$
		toolkit.createLabel(targetObjComposite, ":");
		customObjectButton = toolkit.createButton(targetObjComposite, "",
				SWT.CHECK);
		toolkit.createLabel(targetObjComposite, " ");

		toolkit.createLabel(targetObjComposite, Messages
				.getString("targetDetails.dataConsumerLabel")); //$NON-NLS-1$
		toolkit.createLabel(targetObjComposite, ":");
		GridData dataProducerGridData = new GridData(SWT.FILL, 0, true, false);
		dataProducerGridData.horizontalSpan = 2;
		dataConsumerFunctionText = toolkit.createText(targetObjComposite, "",
				SWT.SINGLE | SWT.BORDER);
		dataConsumerFunctionText.setForeground(null);
		dataConsumerFunctionText.setEnabled(false);
		dataConsumerFunctionText.setLayoutData(dataProducerGridData);
		toolkit.createLabel(targetObjComposite, " ");

		nodeNameText.addKeyListener(new KeyAdapter() {

			private int oldCaretPosition;

			public void keyReleased(KeyEvent e) {
				if (!nodeNameText.getText().equals("")) {
					if (target.getIn() == null
							|| !target.getIn().equals(nodeNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "in", nodeNameText
										.getText());
					}
				} else {
					if (target.getIn() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "in", null);
					}
				}
				oldCaretPosition = nodeNameText.getCaretPosition();
				updateTreeViewer();
				nodeNameText.setSelection(oldCaretPosition);
			}
		});

		nodeNameText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!nodeNameText.getText().equals("")) {
					if (target.getIn() == null
							|| !target.getIn().equals(nodeNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "in", nodeNameText
										.getText());
						updateTreeViewer();
					}
				} else {
					if (target.getIn() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "in", null);
						updateTreeViewer();
					}
				}
			}

		});

		dataTargetNameText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (target.getOut() == null
						|| !target.getOut()
								.equals(dataTargetNameText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							TargetNode.class, target, "out", dataTargetNameText
									.getText());
				}
			}
		});

		dataTargetNameText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!dataTargetNameText.getText().equals("")) {
					if (target.getOut() == null
							|| !target.getOut().equals(
									dataTargetNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "out",
								dataTargetNameText.getText());
					}
				} else {
					if (target.getOut() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "out", null);
					}
				}
			}
		});

		selectDataTargetButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				tool = new UndoableDataBindingTool(masterBlockTreeViewer,
						TargetNode.class, target, "out");

				tool.registerCallback(callbackRefrence);

				graphicalViewer.getEditDomain().setActiveTool(tool);
			}
		});

		customObjectButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				dataConsumerFunctionText.setEnabled(customObjectButton
						.getSelection());
				if (customObjectButton.getSelection() == false) {
					dataConsumerFunctionText.setText("");
					if (target.getTeleType() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "teleType", null);
					}
				}
				super.widgetSelected(e);
			}
		});

		dataConsumerFunctionText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (target.getTeleType() == null
						|| !target.getTeleType().equals(
								dataConsumerFunctionText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							TargetNode.class, target, "teleType",
							dataConsumerFunctionText.getText());
				}
			}
		});

		dataConsumerFunctionText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!dataConsumerFunctionText.getText().equals("")) {
					if (target.getTeleType() == null
							|| !target.getTeleType().equals(
									dataConsumerFunctionText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "teleType",
								dataConsumerFunctionText.getText());
					}
				} else {
					if (target.getTeleType() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								TargetNode.class, target, "teleType", null);
					}
				}
			}
		});

		targetNodeSection.setClient(sourceNodeComposite);
		targetObjSection.setClient(targetObjComposite);
	}

	protected void initializeInterface() {
		update();
		setStaleFlag(false);
	}

	public void update() {
		if (target.getIn() != null) {
			nodeNameText.setText(target.getIn());
		} else {
			nodeNameText.setText("");
		}

		if (target.getOut() != null) {
			dataTargetNameText.setText(target.getOut());
		} else {
			dataTargetNameText.setText("");
		}

		if (target.getTeleType() != null) {
			customObjectButton.setSelection(true);
			dataConsumerFunctionText.setEnabled(true);
			dataConsumerFunctionText.setText(target.getTeleType());
		} else {
			customObjectButton.setSelection(false);
			dataConsumerFunctionText.setEnabled(false);
			dataConsumerFunctionText.setText("");
		}

		this.setDirtyFlag(false);
	}

	public void setTarget(Target target) {
		this.target = target;
	}

	private void updateTreeViewer() {
		masterBlockTreeViewer.expandToLevel(2);
		ITreeNode treeNode = EventPropertiesMasterDetailsBlock.getTreeNode(
				target, TargetNode.class);
		if (treeNode != null) {
			masterBlockTreeViewer.refresh(treeNode, true);
			masterBlockTreeViewer.setSelection(
					new StructuredSelection(treeNode), true);
		}
	}

	public void callback(boolean componentHasBeenSelected) {
		if (target.getOut() != null) {
			dataTargetNameText.setText(target.getOut());
		}

		EditDomain domain = graphicalViewer.getEditDomain();
		Tool defaultTool = domain.getDefaultTool();
		domain.setActiveTool(defaultTool);

		if (componentHasBeenSelected) {
			setDirtyFlag(true);
			update();
			updateTreeViewer();
		}
	}

	public void setGraphicalViewer(GraphicalViewer graphicalViewer) {
		this.graphicalViewer = graphicalViewer;
	}
}
