package geisplugin.popup.actions;

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;

import geisplugin.Tools;

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

public class LinkClassWithManagedbeans 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 (final Object firstElement : ((IStructuredSelection) HandlerUtil.getActiveMenuSelection(event)).toList()) {
			try {
				if (firstElement instanceof ICompilationUnit) {
					createOutput(shell, (ICompilationUnit) firstElement);
				} else {
					MessageDialog.openInformation(shell, "Info", "Please select a Java source file");
				}
			} catch (Exception e) {
				MessageDialog.openError(shell, "Error", "Error " + e.getMessage());
			}
		}
		return null;
	}

	private void createOutput(final Shell shell, final ICompilationUnit element) {
		final String file = element.getResource().getRawLocation().toString();

		//MessageDialog.openInformation(shell, "file", file);

		int i = 0;

		try {

			String fileAsString = Tools.read(file);

			i = 1;

			if (!fileAsString.contains("@CCGenClass (expressionBase=\"")) {
				i = 2;
				MessageDialog.openError(shell, "Error", "This is no CCGenClass");
				return;
			}

			i = 3;
			int index = fileAsString.indexOf("@CCGenClass (expressionBase=\"") + 29;
			i = 4;
			String expression = fileAsString.substring(index);
			i = 5;
			index = expression.indexOf('"');
			i = 6;
			expression = expression.substring(0, index);
			expression = expression.substring(expression.indexOf('.') + 1, expression.length() - 1);
			i = 7;

			//Path vom Projekt
			// -> nicht direkt möglich, aber im CC eigentlich immer in /src/managedbeans/dispatcherinfo.xml

			String dispatcherInfo = file.substring(0, file.indexOf("/src") + 4) + "/managedbeans/dispatcherinfo.xml";

			i = 8;

			//verlinkte .xmls finden -> rekursiv
			//	manuelle Suche vs. XML-DOM API

			//alle .xmls anzeigen und auswählbar machen -> ähnlich der Tabellen-/DB-Auswahl

			String packageStr = fileAsString.substring(fileAsString.indexOf("package") + 8);
			packageStr = packageStr.substring(0, packageStr.indexOf(';'));
			//MessageDialog.openInformation(shell, "packageStr", packageStr);

			i = 9;

			String classStr = file.substring(file.lastIndexOf("/") + 1);
			classStr = classStr.substring(0, classStr.lastIndexOf('.'));
			//MessageDialog.openInformation(shell, "classStr", classStr);

			i = 10;

			String content = Tools.read(dispatcherInfo);

			i = 11;

			content = content.substring(0, content.lastIndexOf("</dispatcherinfo>")).trim() + "\r\n\t<managedbean name=\"" + expression + "\" class=\"" + packageStr + '.' + classStr + "\"/>\r\n\r\n</dispatcherinfo>";

			i = 12;

			Tools.writeNoPathCreation(dispatcherInfo, content);

			i = 13;

			Tools.getCurrentSelectedProject().refreshLocal(IResource.DEPTH_INFINITE, null);
		} catch (final Exception e) {
			MessageDialog.openError(shell, "Error", "Error Code: " + i + ", Line: " + e.getStackTrace()[0].getLineNumber() + ", Message: " + e.getMessage());
		}
	}
}
