package org.erlide.wrangler.refactoring.ui;

import java.util.ArrayList;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.erlide.wrangler.refactoring.core.WranglerRefactoring;
import org.erlide.wrangler.refactoring.core.internal.CaseFunRefactoring;
import org.erlide.wrangler.refactoring.core.internal.ImportRefactoring;
import org.erlide.wrangler.refactoring.core.internal.ListaRefactoring;
import org.erlide.wrangler.refactoring.core.internal.ProvaRefactoring;
import org.erlide.wrangler.refactoring.ui.wizard.DefaultWranglerRefactoringWizard;
import org.erlide.wrangler.refactoring.ui.wizardpages.WranglerPage;
import org.erlide.wrangler.refactoring.util.GlobalParameters;
import org.erlide.wrangler.refactoring.util.WranglerUtils;

public class RefactoringHandler extends AbstractHandler {

	public Object execute(ExecutionEvent event) throws ExecutionException {
		GlobalParameters.setSelection(PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getActivePage().getSelection());

		DefaultWranglerRefactoringWizard wizard = null;
		WranglerRefactoring refactoring = null;
		String actionId = event.getCommand().getId();

		ArrayList<WranglerPage> pages = new ArrayList<WranglerPage>();

			// run lista function refactoring
		if (actionId.equals("org.erlide.wrangler.refactoring.lista")) {
			refactoring = new ListaRefactoring();

			// run import function refactoring
		} else if (actionId.equals("org.erlide.wrangler.refactoring.import")) {
			refactoring = new ImportRefactoring();

			// run import function refactoring
		} else if (actionId.equals("org.erlide.wrangler.refactoring.caseFun")) {
			refactoring = new CaseFunRefactoring();

		} else
			return null;

		// run the given refactoring's wizard
		wizard = new DefaultWranglerRefactoringWizard(refactoring,
		// RefactoringWizard.DIALOG_BASED_USER_INTERFACE, pages);
				RefactoringWizard.NO_PREVIEW_PAGE, pages);

		Shell shell = new Shell();
		RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(
				wizard);

		try {
			int ret = op.run(shell, refactoring.getName());
			if (RefactoringStatus.OK == ret)
				WranglerUtils.notifyErlide(refactoring.getChangedFiles());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;

	}
}
