package geisplugin.popup.actions;

import geisplugin.Activator;
import geisplugin.Tools;

import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.JOptionPane;
import javax.swing.filechooser.FileSystemView;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
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 GetTableMetaData extends AbstractHandler {

	public static void main(final String[] args) {
		try {
			new GetTableMetaData().getTableMetaData();
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
		} 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();
			}
		}
		
	}

	@Override
	public Object execute(final ExecutionEvent event) throws ExecutionException {
		if (Tools.isNotUpToDate()) {
			return null;
		}
		shell = HandlerUtil.getActiveShell(event);
		try {
			getTableMetaData();
		} 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();
			}
		}
		return null;
	}

	private static Shell shell = null;

	private void getTableMetaData() {
		String[] dbs = null;

		try {
			dbs = Tools.getDBs();
		} catch (Exception e) {
		}

		if (dbs == null || dbs.length == 0) {

			if (shell != null) {
				MessageDialog.openInformation(shell, "Info", "Couldn't find any databases, go sure your AS400 driver does exist and read the plugin documentation!");
			} else {
				JOptionPane.showMessageDialog(Activator.frame, "Couldn't find any databases, go sure your AS400 driver does exist and read the plugin documentation!");
			}
			return;
		}

		String db = (String) JOptionPane.showInputDialog(Activator.frame, "Which Database?", "Select a Database", JOptionPane.PLAIN_MESSAGE, null, dbs, "GEISDTT");

		dbs = null;

		if (db == null) {
			return;
		}

		//url = "jdbc:as400://as400;libraries=" + db + ";metadata source=0";

		db = db.substring(0, db.indexOf(" - "));
		
		getTables(db);
	}

	private void getTables(final String db) {

		String outputFilePath = FileSystemView.getFileSystemView().getHomeDirectory() + "\\" + db + "_tables_metadata.xls";
		//System.out.println(outputFilePath);
		Connection jdbc = null;
		WritableWorkbook workbook = null;

		try {
			workbook = Workbook.createWorkbook(new File(outputFilePath));
			jdbc = Tools.getConnection();

			WritableSheet sheet = workbook.createSheet(db, 0);

			sheet.setColumnView(0, 15);
			sheet.addCell(new Label(0, 0, "Table Name"));
			sheet.setColumnView(1, 60);
			sheet.addCell(new Label(1, 0, "Remarks"));

			ResultSet rs = jdbc.getMetaData().getTables("GEISDB01", db, null, new String[] { "TABLE" });
			int i = 1;
			while (rs.next()) {
				sheet.addCell(new Label(0, i, rs.getString(3)));
				sheet.addCell(new Label(1, i, rs.getString(5)));
				i++;
			}

			try {
				workbook.write();
				workbook.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

			rs.close();
			if (rs != null) {
				rs.close();
				rs = null;
			}

			try {
				Desktop.getDesktop().open(new File(outputFilePath));
			} catch (IOException e) {
				if (shell != null) {
					MessageDialog.openInformation(shell, "Info", "Done, exported " + outputFilePath);
				} else {
					JOptionPane.showMessageDialog(Activator.frame, "Done, exported " + outputFilePath);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}