/* 
-*- 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.queries;

import java.util.List;
import java.util.SortedMap;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.ITextSelection;
import org.eclipse.jface.text.TextSelection;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.progress.UIJob;
import org.eclipse.ui.texteditor.ITextEditor;

import com.refactorerl.ui.logic.queries.QueryRequest;
import com.refactorerl.ui.logic.queries.QueryResultElement;
import com.refactorerl.ui.presentation.Activator;
import com.refactorerl.ui.presentation.codebrowser.RemoteTemporaryFileEditorInput;
import com.refactorerl.ui.presentation.codebrowser.StringInput;
import com.refactorerl.ui.presentation.codebrowser.StringStorage;

// NOTE executeRelativeQuery relies on the implementation of ShowFileHandler
/**
 * This handler executes queries based on the command parameters passed in
 * {@code com.refactorerl.ui.queryParameter}.
 * 
 * If the parameter is {@code global} , the string of the query should also be
 * passed in {@code com.refactorerl.ui.queryContentParameter}.
 * 
 * If the parameter is {@code file}, the handler will lookup the filename of the
 * currently active editor, opens a user dialog and executes the query given by
 * the user relative to the file.
 * 
 * The  {@code position} parameter is the same as {@code file}, but in this case the handler
 * also looks up the current cursor position of the currently active editor and
 * the executed query will be relative to the file and the position. 
 * @author Daniel Lukacs, 2014 ELTE IK
 *
 */
public class QueryHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {

		final IWorkbenchWindow wb = HandlerUtil.getActiveWorkbenchWindow(event);

		String parameter = event.getParameter("com.refactorerl.ui.queryParameter"); //$NON-NLS-1$

		if (parameter == null) {

			QueryDialog dialog = new QueryDialog(wb.getShell(), Messages.QueryHandler_1, Messages.QueryHandler_2);
			if (dialog.open() == QueryDialog.OK) {
				executeQuery(wb, dialog.getValue(), null, null);
			}
		} else if (parameter.equals("position")) { //$NON-NLS-1$
			executeRelativeQuery(event, false);
		} else if (parameter.equals("file")) { //$NON-NLS-1$
			executeRelativeQuery(event, true);
		} else if (parameter.equals("global")) { //$NON-NLS-1$
			String query = event.getParameter("com.refactorerl.ui.queryContentParameter"); //$NON-NLS-1$
			executeQuery(wb, query, null, null);
		}

		return null;
	}

	private void executeQuery(final IWorkbenchWindow wb, final String query, final String filePath, final Integer position) {
		new Job(Messages.QueryHandler_7 + query) {

			@Override
			protected IStatus run(IProgressMonitor monitor) {

				final SortedMap<String, List<QueryResultElement>> result;
				QueryRequest request = null;
				if (filePath != null && position != null)
					request = new QueryRequest(filePath, position, query, true, Activator.getProxy(), null);
				else if (filePath != null)
					request = new QueryRequest(filePath, query, true, Activator.getProxy(), null);
				else
					request = new QueryRequest(query, true, Activator.getProxy(), null);

				result = Activator.executeRequest(request, wb.getShell());

				wb.getShell().getDisplay().syncExec(new Runnable() {

					@Override
					public void run() {
						showQueryResults(query.toString(), wb, result);

					}
				});

				return Status.OK_STATUS;
			}

		}.schedule();

	}

	static public void showQueryResults(final String query, final IWorkbenchWindow wb,
			final SortedMap<String, List<QueryResultElement>> result) {

		new UIJob(Messages.QueryHandler_8) {

			@Override
			public IStatus runInUIThread(IProgressMonitor monitor) {
				IWorkbenchPage activePage = wb.getActivePage();
				try {

					// QueryResultView view = (QueryResultView)
					// activePage
					// .showView("com.refactorerl.ui.queryResultView");

					QueryResultView view = (QueryResultView) activePage.showView("com.refactorerl.ui.queryResultView", //$NON-NLS-1$
							query.toString(), IWorkbenchPage.VIEW_ACTIVATE);

					view.setPartName(query.toString());

					view.setInput(result);
					view.setFocus();

				} catch (PartInitException e0) {
					Activator.showErrorDialog(e0, wb.getShell());
				}

				return Status.OK_STATUS;
			}
		}.schedule();
	}

	private void executeRelativeQuery(ExecutionEvent event, boolean fileOnly) {
		final IWorkbenchWindow wb = HandlerUtil.getActiveWorkbenchWindow(event);
		IEditorPart part = HandlerUtil.getActiveEditor(event);
		if (part instanceof ITextEditor) {
			final ITextEditor editor = (ITextEditor) part;

			ISelection sel = editor.getSelectionProvider().getSelection();
			if (sel instanceof TextSelection) {
				IPath path = null;
				if (editor.getEditorInput() instanceof RemoteTemporaryFileEditorInput) {
					RemoteTemporaryFileEditorInput input = (RemoteTemporaryFileEditorInput) editor.getEditorInput();
					path = input.getRemoteFilePath();
				} else if (editor.getEditorInput() instanceof FileEditorInput) { 
					FileEditorInput input = (FileEditorInput) editor.getEditorInput();
					path = input.getFile().getLocation();
				} else if (editor instanceof StringInput) {
					StringInput input = (StringInput) editor.getEditorInput();
					path = ((StringStorage) input.getStorage()).getFullPath();
				} else {
					MessageDialog.openError(wb.getShell(), Messages.QueryHandler_10, Messages.QueryHandler_11);
				}

				String filePath = path.toString();

				String dialogMessage = Messages.QueryHandler_12 + path.lastSegment();

				Integer startPos = 0;
				if (!fileOnly) {
					ITextSelection textSel = (ITextSelection) sel;
					startPos = textSel.getOffset();
					// int endPos = startPos + textSel.getLength();

					dialogMessage += Messages.QueryHandler_13 + startPos;
				}

				QueryDialog dialog = new QueryDialog(editor.getSite().getShell(), Messages.QueryHandler_14,
						dialogMessage);

				dialog.open();
				String query = ""; //$NON-NLS-1$
				if (dialog.getReturnCode() == InputDialog.OK)
					query = dialog.getValue();
				else
					return;

				if (query.trim().length() <= 0)
					return;

				if (fileOnly)
					startPos = null;

				executeQuery(wb, query, filePath, startPos);

			}
		}
	}

}
