package de.ugoe.cs.eventbench.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;


import de.ugoe.cs.util.console.CommandExecuter;

/**
 * <p>
 * Implements the composite for the console tab in the applications main window. 
 * </p>
 * 
 * @author Steffen Herbold
 * @version 1.0
 */
public class ConsoleTabComposite extends Composite {

	protected Text textCommand;
	
	protected StyledText textConsoleOutput;
	
	/**
	 * Create the composite.
	 * @param parent
	 * @param style
	 */
	public ConsoleTabComposite(Composite parent, int style) {
		super(parent, style);
		createContents();
	}
	
	private void createContents() {
		setLayout(new GridLayout(3, false));
		
		Label lblCommand = new Label(this, SWT.NONE);
		lblCommand.setText("Command:");
		
		textCommand = new Text(this, SWT.BORDER);
		textCommand.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				if( e.keyCode==SWT.CR ) {
					executeCommand();
				}
			}
		});
		GridData gd_textCommand = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
		gd_textCommand.widthHint = 304;
		textCommand.setLayoutData(gd_textCommand);
		textCommand.setFocus();
		
		Button btnEnter = new Button(this, SWT.NONE);
		btnEnter.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				executeCommand();
			}
		});
		btnEnter.setText("Enter");
		
		textConsoleOutput = new StyledText(this, SWT.BORDER | SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL);
		GridData gd_textConsoleOutput = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
		gd_textConsoleOutput.heightHint = 102;
		gd_textConsoleOutput.widthHint = 456;
		textConsoleOutput.setLayoutData(gd_textConsoleOutput);
	}
	
	private void executeCommand() {
		String command = textCommand.getText().trim();
		CommandExecuter.getInstance().exec(command);
		textCommand.setText("");
	}

	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

}
