package geisplugin.popup.actions;


import java.awt.Desktop;
import java.io.File;
import java.sql.SQLException;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;

import geisplugin.Activator;
import geisplugin.Tools;

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

public class Decompile extends AbstractHandler {
	
	public static void main(final String[] args) {
		new Decompile().execute(null);
		System.exit(0);
	}
	
	public static String createStringStackTrace(final Throwable e) {
		final StringBuilder stackTrace = new StringBuilder();
		stackTrace.append(e.getClass().getName());
		if (e.getMessage() != null && !e.getMessage().trim().isEmpty()) {
			stackTrace.append(": ");
			stackTrace.append(e.getMessage());
		}
		for (final StackTraceElement element : e.getStackTrace()) {
			stackTrace.append("\tat ");
			stackTrace.append(element.toString());
			stackTrace.append('\n');
		}
		return stackTrace.toString();
	}

	@Override
	public Object execute(final ExecutionEvent event) {
		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();
			}
		}
		try {
			JFileChooser chooser = new JFileChooser();
			FileNameExtensionFilter filter = new FileNameExtensionFilter("Java Files (*.jar, *.class)", "jar", "class");
			chooser.setFileFilter(filter);
			chooser.setAcceptAllFileFilterUsed(false);
			if (chooser.showOpenDialog(Activator.frame) == JFileChooser.APPROVE_OPTION) {
				File inputFile = chooser.getSelectedFile();
				if (!inputFile.exists()) {
					JOptionPane.showMessageDialog(Activator.frame, inputFile.getCanonicalPath() + " does not exist!");
					return null;
				}
				File outputFolder = new File(inputFile.getCanonicalPath() + "_sources\\");
				if (!outputFolder.isDirectory() && !outputFolder.mkdir()) {
					JOptionPane.showMessageDialog(Activator.frame, outputFolder.getCanonicalPath() + " can't get created!");
					return null;					
				}
				org.benf.cfr.reader.Main.main(new String[] { inputFile.getCanonicalPath(), "--outputdir", outputFolder.getCanonicalPath() + "\\" });
				Desktop.getDesktop().open(outputFolder);
			}
		} catch (final Throwable e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(Activator.frame, createStringStackTrace(e));
		}
		return null;
	}
}
