/*
 * 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.Label;
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.Event;
import org.maskat.core.event.Result;
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.LocalDataBinding;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class LocalDataBindingDetailsPage extends AbstractMaskatDetailsPage
		implements ISimpleCallbackInterface {

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

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

	private static final String OBJECT_BUTTON_TEXT = Messages
			.getString("localDataBindingDetails.objectButtonLabel"); //$NON-NLS-1$

	// private Section localDatabindingSection;

	private Text dataSourceText;

	private Text dataTargetText;

	private Text dataProducerFunctionText;

	private Button customObjectButton;

	private Label warningLabel;

	private Target target;

	private Button selectDataSourceButton;

	private Button selectDataTargetButton;

	private GraphicalViewer graphicalViewer;

	private DataBindingTool tool;

	private LocalDataBindingDetailsPage callbackRefrence;

	private boolean isCustomObj = false;

	private boolean isEventRemote = false;

	public LocalDataBindingDetailsPage(TreeViewer masterBlockTreeViewer) {
		this.masterBlockTreeViewer = masterBlockTreeViewer;
	}

	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 localDataBindingSection = toolkit.createSection(parent,
				ExpandableComposite.TITLE_BAR | Section.DESCRIPTION);

		localDataBindingSection.setText(SECTION_TEXT);
		localDataBindingSection.setDescription(DESCRIPTION);
		TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL,
				TableWrapData.TOP);
		tableWrapData.grabHorizontal = true;
		localDataBindingSection.setLayoutData(tableWrapData);

		Composite localDatabindingComposite = toolkit
				.createComposite(localDataBindingSection);

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 4;
		localDatabindingComposite.setLayout(gridLayout);

		toolkit.createLabel(localDatabindingComposite, Messages
				.getString("localDataBindingDetails.DataSourceLabel")); //$NON-NLS-1$
		toolkit.createLabel(localDatabindingComposite, ":");
		dataSourceText = toolkit.createText(localDatabindingComposite, "",
				SWT.SINGLE | SWT.BORDER);
		dataSourceText.setLayoutData(new GridData(SWT.FILL, 0, true, false));
		selectDataSourceButton = toolkit.createButton(
				localDatabindingComposite, OBJECT_BUTTON_TEXT, SWT.PUSH);

		toolkit.createLabel(localDatabindingComposite, Messages
				.getString("localDataBindingDetails.DataTargetLabel")); //$NON-NLS-1$
		toolkit.createLabel(localDatabindingComposite, ":");
		dataTargetText = toolkit.createText(localDatabindingComposite, "",
				SWT.SINGLE | SWT.BORDER);
		dataTargetText.setLayoutData(new GridData(SWT.FILL, 0, true, false));
		selectDataTargetButton = toolkit.createButton(
				localDatabindingComposite, OBJECT_BUTTON_TEXT, SWT.PUSH);

		toolkit.createLabel(localDatabindingComposite, Messages
				.getString("localDataBindingDetails.CustomObjLabel")); //$NON-NLS-1$
		toolkit.createLabel(localDatabindingComposite, ":");
		customObjectButton = toolkit.createButton(localDatabindingComposite,
				"", SWT.CHECK);
		toolkit.createLabel(localDatabindingComposite, " ");

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

		warningLabel = toolkit.createLabel(localDatabindingComposite, Messages
				.getString("localDataBindingDetails.warningLabel"), SWT.WRAP); //$NON-NLS-1$

		GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
		gridData.horizontalSpan = 4;
		gridData.widthHint = 300;
		warningLabel.setLayoutData(gridData);

		dataSourceText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (target.getIn() == null
						|| !target.getIn().equals(dataSourceText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							LocalDataBinding.class, target, "in",
							dataSourceText.getText());

					int oldCaretPosition = dataSourceText.getCaretPosition();

					updateTreeViewer();
					dataSourceText.setSelection(oldCaretPosition);
				}
			}
		});

		dataSourceText.addFocusListener(new FocusAdapter() {

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

		selectDataSourceButton.addSelectionListener(new SelectionAdapter() {

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

				tool.registerCallback(callbackRefrence);

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

		dataTargetText.addKeyListener(new KeyAdapter() {

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

					int oldCaretPosition = dataTargetText.getCaretPosition();
					updateTreeViewer();
					dataTargetText.setSelection(oldCaretPosition);
				}
			}
		});

		dataTargetText.addFocusListener(new FocusAdapter() {

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

		selectDataTargetButton.addSelectionListener(new SelectionAdapter() {

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

				tool.registerCallback(callbackRefrence);

				graphicalViewer.getEditDomain().setActiveTool(tool);

			}
		});

		customObjectButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				dataProducerFunctionText.setEnabled(customObjectButton
						.getSelection());
				if (customObjectButton.getSelection() == false) {
					dataProducerFunctionText.setText("");

					if (((Event) ((Result) target.getParent()).getParent())
							.getType().equals("remote")) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "teleType",
								null);
					} else {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "workType",
								null);
					}
				}
				super.widgetSelected(e);
			}
		});

		dataProducerFunctionText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (customObjectButton.getSelection() == true) {
					if (((Event) ((Result) target.getParent()).getParent())
							.getType().equals("remote")) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "teleType",
								dataProducerFunctionText.getText());
					} else {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "workType",
								dataProducerFunctionText.getText());
					}
				}
			}
		});

		dataProducerFunctionText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (customObjectButton.getSelection() == true) {
					if (((Event) ((Result) target.getParent()).getParent())
							.getType().equals("remote")) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "teleType",
								dataProducerFunctionText.getText());
					} else {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								LocalDataBinding.class, target, "workType",
								dataProducerFunctionText.getText());
					}
				}
			}
		});

		localDataBindingSection.setClient(localDatabindingComposite);
	}

	protected void initializeInterface() {
		isEventRemote = false;

		Result result = (Result) target.getParent();
		Event event = (Event) result.getParent();

		if ((event.getType().equals("remote"))) {
			isEventRemote = true;
			warningLabel.setVisible(true);
		} else {
			warningLabel.setVisible(false);
		}

		isCustomObj = false;

		if (target.getTeleType() != null || target.getWorkType() != null) {
			isCustomObj = true;
		}

		if (target.getIn() != null) {
			dataSourceText.setText(target.getIn());
		} else {
			dataSourceText.setText("");
		}
		if (target.getOut() != null) {
			dataTargetText.setText(target.getOut());
		} else {
			dataTargetText.setText("");
		}

		customObjectButton.setSelection(isCustomObj);

		dataProducerFunctionText.setEnabled(isCustomObj);

		if (isEventRemote == true) {
			if (target.getTeleType() != null) {
				dataProducerFunctionText.setText(target.getTeleType());
			} else {
				dataProducerFunctionText.setText("");
			}
		}

		else {
			if (target.getWorkType() != null) {
				dataProducerFunctionText.setText(target.getWorkType());
			} else {
				dataProducerFunctionText.setText("");
			}
		}

		setStaleFlag(false);
	}

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

		dataProducerFunctionText.setEnabled(customObjectButton.getSelection());

		if (isEventRemote == true) {
			if (target.getTeleType() != null) {
				dataProducerFunctionText.setText(target.getTeleType());
			} else {
				dataProducerFunctionText.setText("");
			}
		}

		else {
			if (target.getWorkType() != null) {
				dataProducerFunctionText.setText(target.getWorkType());
			} else {
				dataProducerFunctionText.setText("");
			}
		}

		setDirtyFlag(false);
	}

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

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

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

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

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

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

}
