package geisplugin.popup.actions;

import geisplugin.Tools;

import java.sql.SQLException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.resources.IResource;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.handlers.HandlerUtil;

/**
 * DE: 
 *
 * EN: 
 * 
 * 
 * Program changes
 * **************************************************************************************
 * Date			* Ticket	* KonzFirm	* Responsible	* programmer    *
 * Change										*
 * **************************************************************************************
 *
 * @author huellmante
 * @version 1.0
 *
 */

public class WhiteSpaceAction extends AbstractHandler {

	@SuppressWarnings("restriction")
	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		try {
			if (Tools.isNotUpToDate()) {
				return null;
			} 
		} finally {
			try {
				if (Tools.con != null && !Tools.con.isClosed()) {
					try {
						Tools.con.rollback();
						Tools.con.close();
					} catch (final SQLException e) {
					}
					Tools.con = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		Shell shell = HandlerUtil.getActiveShell(event);
		boolean ok = false;

		for (final Object selection : ((IStructuredSelection) HandlerUtil.getActiveMenuSelection(event)).toList()) {

			String path;

			if (selection instanceof ICompilationUnit) {
				path = ((ICompilationUnit) selection).getResource().getRawLocation().toString().trim();
			} else
				if (selection instanceof org.eclipse.core.internal.resources.File) {
					path = ((org.eclipse.core.internal.resources.File) selection).getRawLocation().toString().trim();
				} else {
					return null;
				}

			try {

				final String input = Tools.read(path);
				final StringBuilder fileAsString = new StringBuilder(input.length());

				for (final String myString : input.split("\n", 0)) {
					fileAsString.append(Tools.trimEnd(myString));
					fileAsString.append('\n');
				}
				fileAsString.setLength(fileAsString.length() - 1);
				Tools.writeNoPathCreation(path, fileAsString.toString());
				Tools.getCurrentSelectedProject().refreshLocal(IResource.DEPTH_INFINITE, null);
				ok = true;
			} catch (final Exception e) {
				MessageDialog.openError(shell, "Exception", "Exception!\n " + e.getMessage());
			}
		}
		if (ok) {
			MessageDialog.openInformation(shell, "Success", "Done!");
		} else {
			MessageDialog.openWarning(shell, "Error", "Couldn't trim selected files");
		}
		return null;
	}
}