package de.ugoe.cs.eventbench.swt;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.LinkedList;

import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;

import de.ugoe.cs.util.StringTools;
import de.ugoe.cs.util.console.CommandExecuter;
import de.ugoe.cs.util.console.Console;
import de.ugoe.cs.util.console.listener.ICommandListener;

import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

public class CommandHistoryDialog extends Dialog implements ICommandListener {
	
	protected java.util.List<String> history = new LinkedList<String>();
	
	protected List commandHistoryList;
	protected Shell shell;
	
	boolean isOpen;

	/**
	 * Create the dialog.
	 * @param parent
	 * @param style
	 */
	public CommandHistoryDialog(Shell parent, int style) {
		super(parent, style);
		setText("Command History");
		isOpen = false;
		Console.getInstance().registerCommandListener(this);
	}

	/**
	 * Open the dialog.
	 */
	public void open() {
		createContents();
		shell.open();
		shell.layout();
		isOpen = true;
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.RESIZE);
		shell.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent arg0) {
				isOpen = false;
			}
		});
		shell.setSize(450, 300);
		shell.setText(getText());
		shell.setLayout(new GridLayout(3, false));
		
		Label lblRecentCommands = new Label(shell, SWT.NONE);
		lblRecentCommands.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
		lblRecentCommands.setText("Recent Commands:");
		new Label(shell, SWT.NONE);
		
		commandHistoryList = new List(shell, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI);
		commandHistoryList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
		for( String command : history ) {
			commandHistoryList.add(command);
		}
		
		Button btnExec = new Button(shell, SWT.NONE);
		btnExec.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				for( String command : commandHistoryList.getSelection() ) {
					CommandExecuter.getInstance().exec(command);
				}
			}
		});
		btnExec.setText("Execute");
		
		Button btnCopyToClipboard = new Button(shell, SWT.NONE);
		btnCopyToClipboard.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
				StringSelection content = new StringSelection(getSelectedCommands());
				clipboard.setContents(content, null);
			}
		});
		btnCopyToClipboard.setText("Copy to Clipboard");
		
		Button btnCreateBatchfile = new Button(shell, SWT.NONE);
		btnCreateBatchfile.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
				String filename = fileDialog.open();
				if( filename!=null ) {
					File file = new File(filename);
					boolean fileCreated;
					try {
						fileCreated = file.createNewFile();
						if (!fileCreated) {
							Console.traceln("Created batchfile " + filename);
						} else {
							Console.traceln("Overwrote file " + filename);
						}
					} catch (IOException e) {
						Console.printerrln("Unable to create file " + filename);
						Console.logException(e);
					}
					OutputStreamWriter writer = null;
					try {
						writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
					} catch (IOException e) {
						Console.printerrln("Unable to open file for writing (read-only file):"
								+ filename);
						Console.logException(e);
						return;
					}
					try {
						writer.write(getSelectedCommands());
						writer.close();
					} catch (IOException e) {
						Console.printerrln("Unable to write to file.");
						Console.logException(e);
					}
				}
			}
		});
		btnCreateBatchfile.setText("Create Batchfile");

	}

	@Override
	public void commandNotification(String command) {
		history.add(command);
		if( isOpen ) {
			commandHistoryList.add(command);
		}
	}
	
	public boolean isOpen() {
		return isOpen;
	}
	
	private String getSelectedCommands() {
		StringBuilder commands = new StringBuilder();
		for( String command : commandHistoryList.getSelection()) {
			commands.append(command + StringTools.ENDLINE);
		}
		return commands.toString();
	}
}
