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 ConvertToUTF8 extends AbstractHandler {

	@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);
		for (Object firstElement : ((IStructuredSelection) HandlerUtil.getActiveMenuSelection(event)).toList()) {
			try {
				if (firstElement instanceof ICompilationUnit) {
					createOutput(shell, firstElement);
				} else {
					MessageDialog.openInformation(shell, "Info", "Please select Java file, not a " + firstElement.getClass().getCanonicalName());
				}
			} catch (Exception e) {
				MessageDialog.openError(shell, "Fehler", "Fehler " + e.getMessage());
			}
		}
		return null;
	}

	private void createOutput(final Shell shell, final Object firstElement) {
		ICompilationUnit cu = (ICompilationUnit) firstElement;
		String file = cu.getResource().getRawLocation().toString();
		try {

			String fileAsString = Tools.read(file);

			Tools.writeUTF8(file, fileAsString);

			Tools.getCurrentSelectedProject().refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (final Exception e) {
			MessageDialog.openError(shell, "Error", "Error!\n " + e.getMessage());
		}

	}
}