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.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
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 GetMetaData extends AbstractHandler {

	public static void main(String[] args) {
		try {
			new GetMetaData().getMetaData();
			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(ExecutionEvent event) throws ExecutionException {
		if (Tools.isNotUpToDate()) {
			return null;
		}
		shell = HandlerUtil.getActiveShell(event);
		try {
			getMetaData();
		} 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 getMetaData() {

		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;
		}
		
		db = db.substring(0, db.indexOf(" - "));
		System.out.println(db);

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

		getMetaDataWholeDBExcel(db, Tools.getTables(db));
	}

	@SuppressWarnings("null")
	private void getMetaDataWholeDBExcel(final String db, final String[] tables) {

		if (tables == null || tables.length == 0) {
			if (shell != null) {
				MessageDialog.openError(shell, "Info", db + " is empty.");
			} else {
				JOptionPane.showMessageDialog(Activator.frame, db + " is empty.");
			}
			return;
		}

		Connection jdbc = null;
		ResultSet rs = null;
		Statement stmt = null;
		WritableWorkbook workbook = null;

		int currentSheet = 0;
		String outputFilePath = FileSystemView.getFileSystemView().getHomeDirectory() + "\\" + db + "_metadata.xls";

		//System.out.println(url);

		DatabaseMetaData dbMetaData = null;
		try {
			workbook = Workbook.createWorkbook(new File(outputFilePath));
			jdbc = Tools.getConnection();
			//System.out.println(url);
			stmt = jdbc.createStatement();

			
			for (String currentTabelle : tables) {
				currentTabelle = currentTabelle.substring(0, currentTabelle.indexOf(" - "));
				dbMetaData = jdbc.getMetaData();
				rs = dbMetaData.getColumns("GEISDB01", db, currentTabelle, null);

				WritableSheet sheet = workbook.createSheet(currentTabelle, currentSheet);
				currentSheet++;

				sheet.setColumnView(0, 13);
				sheet.addCell(new Label(0, 0, "Column Name"));

				sheet.setColumnView(1, 18);
				sheet.addCell(new Label(1, 0, "Column Type Name"));

				sheet.setColumnView(2, 12);
				sheet.addCell(new Label(2, 0, "Column Type"));

				sheet.setColumnView(3, 8);
				sheet.addCell(new Label(3, 0, "Precision"));

				sheet.setColumnView(4, 5);
				sheet.addCell(new Label(4, 0, "Scale"));

				sheet.setColumnView(5, 50);
				sheet.addCell(new Label(5, 0, "Remark"));

				int i = 1;

				while (rs.next()) {
					sheet.addCell(new Label(0, i, rs.getString(4)));//"COLUMN_NAME"
					sheet.addCell(new Label(1, i, rs.getString(6)));//"TYPE_NAME"
					sheet.addCell(new Number(2, i, rs.getInt(5)));//"DATA_TYPE"
					sheet.addCell(new Number(3, i, rs.getInt(7)));//"COLUMN_SIZE"
					sheet.addCell(new Number(4, i, rs.getInt(9)));//"DECIMAL_DIGITS"
					sheet.addCell(new Label(5, i, rs.getString(12)));//"REMARKS"
					i++;
				}

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

			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			dbMetaData = null;
		}
		try {
			workbook.write();
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		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);
			}
		}
	}
}