package data;

import gui.MainFrameController;

import java.awt.Color;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import logging.Log;
import logging.LogLevel;
import database.DatabaseAccess;

/**
 * 
 * @author Martin Pabst, 2010
 * 
 *         Tests asv database and cache database. If latter doesn't exist:
 *         creates it
 * 
 */

public class DatabaseTester {

	/**
	 * is asv database connection OK?
	 */
	private boolean asvDatabaseConnectionOK = false;

	private MainFrameController controller;

	public DatabaseTester(MainFrameController controller) {
		this.controller = controller;
	}

	/**
	 * Tests asv database.
	 */
	public void testASVDatabase() {
		Log.outl("", LogLevel.error);
		Log.outColor("Teste Verbindung zur ASV-Datenbank. Bitte warten...",
				LogLevel.useful, Color.blue);

		Log.setProgressBarMaximum(-1);

		asvDatabaseConnectionOK = false;

		Connection connection = null;

		try {
			DatabaseAccess.getActiveDatabase(false).openConnection();

			connection = DatabaseAccess.getActiveDatabase(false)
					.getConnection();

			/**
			 * We check if table svp_schule is present and has at least one row.
			 */
			String query1 = "SELECT * FROM svp_schule_stamm";
			Statement statement1 = connection.createStatement();
			ResultSet resultSet1 = statement1.executeQuery(query1);

			if (resultSet1.next()) {
				/*
				 * resultSet has at least one entry
				 */
				asvDatabaseConnectionOK = true;
				Log.outlColor("ASV-Datenbank gefunden.", LogLevel.useful,
						new Color(0, 50, 0));

				// ExecuteScriptsWorker esw = new
				// ExecuteScriptsWorker(controller);
				// esw.doInForeground();

			} else {
				Log.outl("", LogLevel.error);
				Log.outlColor(
						"Es kann keine Verbindung zur ASV-Datenbank aufgebaut werden!",
						LogLevel.error, Color.red);
			}
			resultSet1.close();
			statement1.close();

		} catch (Exception ex) {
			Log.outl("", LogLevel.error);
			ex.printStackTrace();
			Log.outlColor(
					"Es kann keine Datenbankverbindung aufgebaut werden!",
					LogLevel.error, Color.red);
			Log.outlColor(ex.toString(), LogLevel.error, Color.red);
		}

		if (asvDatabaseConnectionOK) {
			// makeSchulliste();
		}

		DatabaseAccess.getActiveDatabase(false).closeConnection();

	}

	public boolean isAsvDatabaseConnectionOK() {
		return asvDatabaseConnectionOK;
	}

}
