package de.ugoe.cs.eventbench.swt;

import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class GetObjectNameDialog extends Dialog {

	String objectName = "";
	
	protected Object result;
	protected Shell shlObjectName;
	private Text text;

	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public GetObjectNameDialog(Shell parent, int style) {
		super(parent, style);
		setText("SWT Dialog");
	}

	/**
	 * Open the dialog.
	 * @return the result
	 */
	public Object open() {
		createContents();
		shlObjectName.open();
		shlObjectName.layout();
		Display display = getParent().getDisplay();
		while (!shlObjectName.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shlObjectName = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
		shlObjectName.setSize(171, 109);
		shlObjectName.setText("Object Name");
		shlObjectName.setLayout(new GridLayout(2, false));
		
		Label lblPleaseEnterThe = new Label(shlObjectName, SWT.NONE);
		lblPleaseEnterThe.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		lblPleaseEnterThe.setText("Please enter the object name:");
		
		text = new Text(shlObjectName, SWT.BORDER);
		text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
		
		Button btnOk = new Button(shlObjectName, SWT.NONE);
		btnOk.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if( text.getText().equals("") ) {
					MessageBox messageBox = new MessageBox(shlObjectName, SWT.ERROR);
					messageBox.setText("Error");
					messageBox.setMessage("No name entered!");
					return;
				}
				objectName = text.getText();
				shlObjectName.dispose();
			}
		});
		btnOk.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		btnOk.setText("Ok");
		
		Button btnAbort = new Button(shlObjectName, SWT.NONE);
		btnAbort.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				shlObjectName.dispose();
			}
		});
		btnAbort.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		btnAbort.setText("Abort");

	}
	
	public String getObjectName() {
		return objectName;
	}
}
