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

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.handlers.HandlerUtil;

import com.refactorerl.ui.logic.filelist.AddFileRequest;
import com.refactorerl.ui.presentation.Activator;
/**
 * 
 * @author Daniel Lukacs, 2014 ELTE IK
 *
 */
public class AddFileHandler extends AbstractHandler {

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

		IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow(event)
				.getActivePage();
		Shell shell = activePage.getActivePart().getSite().getShell();

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

		String pathParam = event
				.getParameter("com.refactorerl.ui.addFile.path"); //$NON-NLS-1$

		String filepath;
		
		if(pathParam != null && !pathParam.trim().isEmpty()){
			filepath = pathParam;
			
		} else if (param != null && param.equals("directory")) { //$NON-NLS-1$
			DirectoryDialog dialog = new DirectoryDialog(shell);
			filepath = dialog.open();
		} else {
			FileDialog dialog = new FileDialog(shell);
			filepath = dialog.open();
		}

		if (filepath != null) {		
			Activator.executeRequest(new AddFileRequest(filepath, Activator.getProxy(),
					null), shell);
			shell.getDisplay().asyncExec(new Runnable(){
				@Override
				public void run() {
					FileListView view = (FileListView) HandlerUtil
							.getActiveWorkbenchWindow(event).getActivePage()
							.findView("com.refactorerl.ui.fileListView"); //$NON-NLS-1$
					if (view != null)
						view.reload();
				}						
			});
		}
		return null;
	}
}
