/* 
-*- coding: latin-1 -*-

This file is part of RefactorErl.

RefactorErl is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

RefactorErl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with RefactorErl.  If not, see <http://plc.inf.elte.hu/erlang/>.

The Original Code is RefactorErl.

The Initial Developer of the Original Code is Eötvös Loránd University.
Portions created  by Eötvös Loránd University and ELTE-Soft Ltd.
are Copyright 2007-2025 Eötvös Loránd University, ELTE-Soft Ltd.
and Ericsson Hungary. All Rights Reserved.
*/

package com.refactorerl.ui.presentation.investigations;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.refactorerl.ui.communication.exceptions.ReferlException;
import com.refactorerl.ui.logic.investigations.DeleteInvestigationRequest;
import com.refactorerl.ui.logic.investigations.Investigation;
import com.refactorerl.ui.logic.investigations.InvestigationsFactory;
import com.refactorerl.ui.logic.investigations.LoadInvestigationRequest;
import com.refactorerl.ui.logic.queries.ListQueryRequest;
import com.refactorerl.ui.presentation.Activator;

/**
 * This handler is responsible for loading, creating and deleting
 * investigations. The mode can specified by passing new, delete or load
 * parameters in the com.refactorerl.ui.modifyInvestigation.mode command
 * parameter. If new or delete parameter was passed, the name of the
 * investigations can also be passed in the
 * com.refactorerl.ui.modifyInvestigation.name parameter. If no name parameter
 * was passed the handler will parse the active selection for investigation names.
 * 
 * @author Daniel Lukacs, 2014 ELTE IK
 *
 */
public class ModifyInvestigationHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
		IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
		List<String> investigationNames;
		try {
			String modeParam = event.getParameter("com.refactorerl.ui.modifyInvestigation.mode"); //$NON-NLS-1$

			if (modeParam.equals("new")) { //$NON-NLS-1$

				List<String> proposals = Activator.executeRequest(
						ListQueryRequest.createFunctionListQueryRequest(Activator.getProxy(), null),
						activeWorkbenchWindow.getShell());
				NewEmptyInvestigationDialog dialog = new NewEmptyInvestigationDialog(activePage.getWorkbenchWindow()
						.getShell(), Messages.ModifyInvestigationHandler_2, Messages.ModifyInvestigationHandler_3,
						proposals);
				if (dialog.open() == NewEmptyInvestigationDialog.OK) {
					String name = dialog.getInvestigationName();
					String fun = dialog.getStartFunction();
					if (!name.trim().isEmpty() && !fun.trim().isEmpty()) {
						System.out.println(Arrays.asList());
						String[] mfa = fun.split("[:/]"); //$NON-NLS-1$
						String modName = mfa[0];
						String funName = mfa[1];
						int arity = Integer.parseInt(mfa[2]);

						Investigation inv = InvestigationsFactory.createNewInvestigation(name, Activator.getProxy()
								.getNodeName(), modName, funName, arity, Activator.getProxy(), null);

						InvestigationHelper.showNewInvestigation(inv, activePage);
					}
				}

			} else if (modeParam.equals("load")) { //$NON-NLS-1$
				investigationNames = lookupSelectedInvestigations(event);
				if (investigationNames != null) {
					for (String name : investigationNames) {
						Investigation inv = Activator.executeRequest(
								new LoadInvestigationRequest(name, Activator.getProxy(), null),
								activeWorkbenchWindow.getShell());

						activePage.openEditor(new InvestigationEditorInput(inv),
								"com.refactorerl.ui.investigationEditor"); //$NON-NLS-1$

					}
				}

			} else if (modeParam.equals("delete")) { //$NON-NLS-1$

				investigationNames = lookupSelectedInvestigations(event);
				if (investigationNames != null) {
					boolean b = MessageDialog.openConfirm(activeWorkbenchWindow.getShell(),
							Messages.ModifyInvestigationHandler_8, Messages.ModifyInvestigationHandler_9);
					if (b) {
						for (String name : investigationNames) {
							Activator.executeRequest(new DeleteInvestigationRequest(name, Activator.getProxy(), null),
									activeWorkbenchWindow.getShell());

							IEditorPart editor = activePage.findEditor(new InvestigationEditorInput(new Investigation(
									name, null)));
							if (editor != null && editor instanceof InvestigationEditor) {
								activePage.closeEditor(editor, false);
							}

						}
						((InvestigationsView) activePage.findView("com.refactorerl.ui.investigationsView")) //$NON-NLS-1$
								.refreshList();

					}
				}
			}

		} catch (PartInitException | ReferlException e) {
			Activator.showErrorDialog(e, activeWorkbenchWindow.getShell());
		}
		return null;
	}

	private List<String> lookupSelectedInvestigations(ExecutionEvent event) {
		IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);

		List<String> investigationNames;
		String nameParam = event.getParameter("com.refactorerl.ui.modifyInvestigation.name"); //$NON-NLS-1$

		System.out.println();
		if (nameParam == null) {
			final ISelection selection = activeWorkbenchWindow.getSelectionService().getSelection(
					"com.refactorerl.ui.investigationsView"); //$NON-NLS-1$
			if (selection == null)
				return null;
			investigationNames = ((StructuredSelection) selection).toList();
		} else {
			investigationNames = new ArrayList<>();
			investigationNames.add(nameParam);
		}
		return investigationNames;
	}

}
