package org.postgresforest.tool.tests;

import java.io.*;
import java.sql.*;
import junit.framework.*;

import org.postgresforest.tool.Logger;
import org.postgresforest.tool.lib.Config;
import org.postgresforest.tool.lib.Instance;
import org.postgresforest.tool.lib.GSCdata;
import org.postgresforest.tool.lib.ForestToolException;

public class ForestToolTestCase extends TestCase {
	String user = "forestadmin";
	String pass = "";

	protected boolean dropdb(String dbname, String portNumber)
	{
		boolean rc = false;

		Connection con = null;

		try {
			Class.forName("org.postgresql.Driver");

            Thread.sleep(2000);

			String url = "jdbc:postgresql://localhost:" + portNumber + "/postgres";
			System.out.println(url);

			con = DriverManager.getConnection(url, user, pass);

			con.createStatement().executeUpdate("DROP DATABASE " + dbname);
			rc = true;

            Thread.sleep(2000);
		}
		catch (Exception e)
		{
			Logger.debug(e.getMessage());
			Logger.trace(e);
		}

		try {
			con.close();
		}
		catch (Exception e)
		{
		}

		return rc;
	}

	protected void initializeGSC()
	{
		GSCdata gsc = null;

		dropdb("gsctest", "9998");
		dropdb("gsctest", "9999");
		dropdb("testdb", "9998");
		dropdb("testdb", "9999");

		try {
			gsc = GSCdata.initialize("localhost", "9998", "gsctest",
									 user, pass);
			assertTrue(gsc!=null);
			gsc.close();
		}
		catch (ForestToolException e)
		{
			System.out.println(e.getMessage());
			fail();
		}
	}

	protected boolean executeUpdatePG(String hostName, String portNumber, String dbName, String sql)
	{
		Connection con = null;
		String url = "jdbc:postgresql://" + hostName + ":" + portNumber + "/" + dbName;
		boolean rc = false;

		try {
			con = DriverManager.getConnection(url, user, pass);

			con.createStatement().executeUpdate(sql);
			rc = true;
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			fail();
		}
		finally
		{
			try {
				if ( con!=null )
					con.close();
			}
			catch (Exception e)
			{
				System.out.println(e.getMessage());
			}
		}

		return rc;
	}
}
