/*
 * 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.jface.viewers.ISelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;

public abstract class AbstractMaskatDetailsPage implements IDetailsPage {

	protected TreeViewer masterBlockTreeViewer;

	protected IManagedForm managedForm;

	protected boolean dirtyFlag = false;

	protected boolean staleFlag = true;

	public void createContents(Composite parent) {
	}

	public void commit(boolean onSave) {
	}

	public void dispose() {
	}

	public void initialize(IManagedForm form) {
		this.managedForm = form;
	}

	public boolean isDirty() {
		return dirtyFlag;
	}

	public boolean isStale() {
		return staleFlag;
	}

	public void refresh() {
		initializeInterface();
	}

	abstract protected void initializeInterface();

	public void setFocus() {
	}

	public boolean setFormInput(Object input) {
		return false;
	}

	public void selectionChanged(IFormPart part, ISelection selection) {
		if (isDirty()) {
			update();
		}
	}

	abstract void update();

	public boolean isDirtyFlag() {
		return dirtyFlag;
	}

	public void setDirtyFlag(boolean dirtyFlag) {
		this.dirtyFlag = dirtyFlag;
	}

	public boolean isStaleFlag() {
		return staleFlag;
	}

	public void setStaleFlag(boolean staleFlag) {
		this.staleFlag = staleFlag;
	}

	protected boolean isTextValueValid(Text textField) {
		try {
			new Integer(textField.getText()).intValue();
		} catch (NumberFormatException exception) {
			return false;
		}
		return true;
	}

	protected int getTextValueAsIntValue(Text textField, int originalValue) {
		int returnValue = originalValue;
		try {
			returnValue = new Integer(textField.getText()).intValue();
		} catch (NumberFormatException exception) {
		}

		return returnValue;
	}

	protected class VerifyIntegerListener implements Listener {

		public void handleEvent(org.eclipse.swt.widgets.Event e) {
			String string = e.text;
			char[] chars = new char[string.length()];
			string.getChars(0, chars.length, chars, 0);
			for (int i = 0; i < chars.length; i++) {
				if (!('0' <= chars[i] && chars[i] <= '9')) {
					e.doit = false;
					return;
				}
			}
		}
	}
}
