/*
 * 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.Source;
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.SourceNode;
import org.maskat.ui.views.properties.tabbed.treenodewrapper.ITreeNode;

public class SourceDetailsPage extends AbstractMaskatDetailsPage implements
		ISimpleCallbackInterface {

	private static final String SOURCE_NODE_SECTION_TEXT = Messages
			.getString("souceDetails.sourceSectionText"); //$NON-NLS-1$

	private static final String SOURCE_NODE_DESCRIPTION = Messages
			.getString("souceDetails.sourceDescription"); //$NON-NLS-1$

	private static final String DATA_TARGET_SECTION_TEXT = Messages
			.getString("souceDetails.targetSectionText"); //$NON-NLS-1$

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

	private SourceNode sourceNode;

	private Text nodeNameText;

	private Button sendBlankElementButton;

	private Button customObjectButton;

	private Text dataProducerFunctionText;

	private Text cellIndexText;

	private Text dataSourceNameText;

	private Text alternativeDataSourceNameText;

	private Source source;

	private int lastFromKeyValue;

	private Button selectDataSourceButton;

	private Button selectAlternativeDataSourceButton;

	protected DataBindingTool tool;

	protected ISimpleCallbackInterface callbackRefrence;

	private GraphicalViewer graphicalViewer;

	private boolean alternativeDataSourceButton = false;

	private boolean dataSourceButton = false;

	public SourceDetailsPage(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 sourceNodeSection = toolkit.createSection(parent,
				ExpandableComposite.TITLE_BAR | Section.DESCRIPTION);
		sourceNodeSection.setText(SOURCE_NODE_SECTION_TEXT);
		sourceNodeSection.setDescription(SOURCE_NODE_DESCRIPTION);
		TableWrapData tableWrapData = new TableWrapData(TableWrapData.FILL,
				TableWrapData.TOP);
		tableWrapData.grabHorizontal = true;
		sourceNodeSection.setLayoutData(tableWrapData);

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

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

		toolkit.createLabel(sourceNodeComposite, Messages
				.getString("souceDetails.sendBlankLabel")); //$NON-NLS-1$
		toolkit.createLabel(sourceNodeComposite, ":");
		sendBlankElementButton = toolkit.createButton(sourceNodeComposite, "",
				SWT.CHECK);

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

		Composite dataSourceObjComposite = toolkit
				.createComposite(dataSourceSection);
		dataSourceObjComposite.setLayout(new GridLayout(4, false));

		/**/
		toolkit.createLabel(dataSourceObjComposite, Messages
				.getString("souceDetails.dataSourceLabel")); //$NON-NLS-1$
		toolkit.createLabel(dataSourceObjComposite, ":");
		dataSourceNameText = toolkit.createText(dataSourceObjComposite, "");
		GridData gridData = new GridData(SWT.FILL, 0, true, false);
		dataSourceNameText.setLayoutData(gridData);
		selectDataSourceButton = toolkit
				.createButton(
						dataSourceObjComposite,
						Messages
								.getString("souceDetails.dataSourceButtonLabel"), SWT.BUTTON1); //$NON-NLS-1$

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

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

		/**/
		// cellIndexLabel = toolkit.createLabel(dataSourceObjComposite, "Cell
		// index");
		// cellIndexColon = toolkit.createLabel(dataSourceObjComposite, ":");
		toolkit.createLabel(dataSourceObjComposite, Messages
				.getString("souceDetails.callIndexLabel")); //$NON-NLS-1$
		toolkit.createLabel(dataSourceObjComposite, ":");
		cellIndexText = toolkit.createText(dataSourceObjComposite, "",
				SWT.SINGLE | SWT.BORDER);
		cellIndexText.setForeground(null);
		gridData = new GridData(SWT.FILL, 0, true, false);
		gridData.horizontalSpan = 2;
		cellIndexText.setLayoutData(gridData);

		/**/
		toolkit.createLabel(dataSourceObjComposite, Messages
				.getString("souceDetails.alternativeDataLabel")); //$NON-NLS-1$
		toolkit.createLabel(dataSourceObjComposite, ":");
		alternativeDataSourceNameText = toolkit.createText(
				dataSourceObjComposite, "");
		gridData = new GridData(SWT.FILL, 0, true, false);
		alternativeDataSourceNameText.setLayoutData(gridData);
		alternativeDataSourceNameText.setForeground(null);
		selectAlternativeDataSourceButton = toolkit
				.createButton(
						dataSourceObjComposite,
						Messages
								.getString("souceDetails.alternativeDataSourceButtonLabel"), //$NON-NLS-1$
						SWT.BUTTON1);

		nodeNameText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (source.getNode() == null
						|| !source.getNode().equals(nodeNameText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "node", nodeNameText
									.getText());

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

		nodeNameText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!nodeNameText.getText().equals("")) {
					if (source.getNode() == null
							|| !source.getNode().equals(nodeNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "node", nodeNameText
										.getText());
					}
				} else {
					if (source.getNode() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "node", null);
					}
				}
				// updateTreeViewer();
			}
		});

		sendBlankElementButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				if (source.isSendBlankElement() != sendBlankElementButton
						.getSelection()) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "sendBlankElement",
							String.valueOf(sendBlankElementButton
									.getSelection()));
				}
			}
		});

		dataSourceNameText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (source.getObj() == null
						|| !source.getObj()
								.equals(dataSourceNameText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "obj", dataSourceNameText
									.getText());
				}
			}
		});

		dataSourceNameText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!dataSourceNameText.getText().equals("")) {
					if (source.getObj() == null
							|| !source.getObj().equals(
									dataSourceNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "obj",
								dataSourceNameText.getText());
					}
				} else {
					if (source.getObj() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "obj", "");
					}
				}
			}
		});

		selectDataSourceButton.addSelectionListener(new SelectionAdapter() {

			public void widgetSelected(SelectionEvent e) {
				alternativeDataSourceButton = false;
				dataSourceButton = true;

				tool = new UndoableDataBindingTool(masterBlockTreeViewer,
						SourceNode.class, source, "obj");

				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("");
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "teleType", null);
				}
				super.widgetSelected(e);
			}
		});

		dataProducerFunctionText.addKeyListener(new KeyAdapter() {

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

		dataProducerFunctionText.addFocusListener(new FocusAdapter() {

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

		cellIndexText.addListener(SWT.Verify, new VerifyIntegerListener());
		cellIndexText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (source.getFromkey() != cellIndexTextAsIntValue()) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "fromkey", new Integer(
									cellIndexTextAsIntValue()).toString());
				}
			}
		});

		cellIndexText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!cellIndexText.getText().equals("")) {
					if (source.getFromkey() != cellIndexTextAsIntValue()) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "fromkey",
								new Integer(cellIndexTextAsIntValue())
										.toString());
					}

					if (source.getFromkey() > -1) {
						cellIndexText.setText(new Integer(
								cellIndexTextAsIntValue()).toString());
					} else {
						cellIndexText.setText("");
					}
				} else {
					if (source.getFromkey() != -1) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "fromkey", "-1");
					}
				}
			}
		});
		alternativeDataSourceNameText.addKeyListener(new KeyAdapter() {

			public void keyReleased(KeyEvent e) {
				if (source.getIdxRef() == null
						|| !source.getIdxRef().equals(
								alternativeDataSourceNameText.getText())) {
					EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
							SourceNode.class, source, "idxRef",
							alternativeDataSourceNameText.getText());
				}
			}
		});

		alternativeDataSourceNameText.addFocusListener(new FocusAdapter() {

			public void focusLost(FocusEvent e) {
				if (!alternativeDataSourceNameText.getText().equals("")) {
					if (source.getIdxRef() == null
							|| !source.getIdxRef().equals(
									alternativeDataSourceNameText.getText())) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "idxRef",
								alternativeDataSourceNameText.getText());
					}
				} else {
					if (source.getIdxRef() != null) {
						EventPropertiesMasterDetailsBlock.setEventProperty(masterBlockTreeViewer,
								SourceNode.class, source, "idxRef", "");
					}
				}
			}
		});

		selectAlternativeDataSourceButton
				.addSelectionListener(new SelectionAdapter() {

					public void widgetSelected(SelectionEvent e) {
						alternativeDataSourceButton = true;
						dataSourceButton = false;

						tool = new UndoableDataBindingTool(
								masterBlockTreeViewer, SourceNode.class,
								source, "idxRef");

						tool.registerCallback(callbackRefrence);

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

		sourceNodeSection.setClient(sourceNodeComposite);
		dataSourceSection.setClient(dataSourceObjComposite);
	}

	private int cellIndexTextAsIntValue() {
		int returnValue = lastFromKeyValue;

		try {
			returnValue = new Integer(cellIndexText.getText()).intValue();
		} catch (NumberFormatException ex) { // is also thrown when number is
			// to long!

		}

		lastFromKeyValue = returnValue;

		return returnValue;
	}

	protected void update() {
		if (source.getNode() != null) {
			nodeNameText.setText(source.getNode());
		} else {
			nodeNameText.setText("");
		}

		sendBlankElementButton.setSelection(source.isSendBlankElement());

		if (source.getObj() != null) {
			dataSourceNameText.setText(source.getObj());
		} else {
			dataSourceNameText.setText("");
		}

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

		if (source.getBindsIt() != null || source.getChildNode() != null) {
			cellIndexText.setText("");
			cellIndexText.setEnabled(false);
		} else {
			cellIndexText.setEnabled(true);
			if (source.getFromkey() > -1) {
				cellIndexText.setText((new Integer(source.getFromkey()))
						.toString());
			} else {
				cellIndexText.setText("");
			}
		}

		if (source.getIdxRef() != null) {
			alternativeDataSourceNameText.setText(source.getIdxRef());
		} else {
			alternativeDataSourceNameText.setText("");
		}

		setDirtyFlag(false);
	}

	public void setSource(SourceNode sourceNode) {
		this.sourceNode = sourceNode;
	}

	protected void initializeInterface() {
		source = (Source) sourceNode.getModel();

		lastFromKeyValue = source.getFromkey();

		update();
		setStaleFlag(false);
	}

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

	public void callback(boolean componentHasBeenSelected) {
		if (dataSourceButton == true && alternativeDataSourceButton == false) {
			if (source.getObj() != null) {
				dataSourceNameText.setText(source.getObj());
			}

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

			if (componentHasBeenSelected) {
				dataSourceButton = false;
				setDirtyFlag(true);
				update();
				updateTreeViewer();
			}
		} else if (dataSourceButton == false
				&& alternativeDataSourceButton == true) {
			if (source.getIdxRef() != null) {
				alternativeDataSourceNameText.setText(source.getIdxRef());
			}

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

			if (componentHasBeenSelected) {
				alternativeDataSourceButton = false;
				setDirtyFlag(true);
				update();
				updateTreeViewer();
			}
		}
	}

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

}
