package edu.fichte.pbi.ide.commands;

import java.io.File;
import java.io.IOException;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import edu.fichte.pbi.ide.editors.FileSystemFileEditorInput;
import edu.fichte.pbi.ide.editors.PBIEditor;

public class NewFileCommandHandler implements IHandler {

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
		FileDialog fileDialog = new FileDialog(window.getShell(), SWT.SAVE);
		fileDialog.setFileName("new.bs1");
		fileDialog.setFilterExtensions(new String[] { "*.bs1" });
		// fileDialog.setFileName(fileInput.getName());
		// fileDialog.setFilterPath(fileInput.getFile().getParent());
		String newFile = fileDialog.open();
		File file = new File(newFile);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		FileSystemFileEditorInput fileSystemFileEditorInput = new FileSystemFileEditorInput(
				file);
		try {
			PBIEditor editor = (PBIEditor) window.getActivePage().openEditor(fileSystemFileEditorInput,
					PBIEditor.ID);
			if(editor.text.getText().isEmpty()){
				editor.text.setText("' {$STAMP BS1}");
			}
		} catch (PartInitException e) {
			e.printStackTrace();
		}

		// setInput(fileSystemFileEditorInput);
		// doSave(null);
		return null;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isHandled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

}
