package org.postgresforest.tool.tests;

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

import org.postgresforest.tool.lib.Config;
import org.postgresforest.tool.lib.Database;
import org.postgresforest.tool.lib.Instance;
import org.postgresforest.tool.lib.Table;
import org.postgresforest.tool.lib.GSCdata;
import org.postgresforest.tool.lib.Instance;
import org.postgresforest.tool.lib.ForestToolException;

public class TestInstance extends TestCase {
	String user = "snaga";
	String pass = "";

	public void setUp()
	{
	}

	public void tearDown()
	{
	}

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

		try {
            Thread.sleep(2000);

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

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

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

            Thread.sleep(2000);
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
		}

		return rc;
	}

    private boolean executeDDL(String dbName, String portNumber, String sql)
    {
        boolean rc = false;

        try {
            String url = "jdbc:postgresql://localhost:" + portNumber + "/" + dbName;

            Connection con = DriverManager.getConnection(url, user, pass);
            con.createStatement().executeUpdate(sql);
            con.close();
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
			return false;
        }

		return true;
    }


	public void testInitialize001()
	{
		GSCdata gsc = null;

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

		try {
			gsc = GSCdata.initialize("localhost", "9998", "gsctest",
									 user, pass);
			assertTrue(gsc!=null);

			gsc.registerInstance("localhost", "9999");

			Database d1 = gsc.createDatabase("testdb");
			Database d2 = gsc.createDatabase("testdb2");

			gsc.close();
		}
		catch (ForestToolException e)
		{
			System.out.println(e.getMessage());
			fail();
		}
	}


	public void testGetDatabaseNames001()
	{
		GSCdata gsc = null;

		try {
			gsc = new GSCdata("localhost", "9998", "gsctest",
							  user, pass);
			assertTrue(gsc!=null);

			Instance i = gsc.getInstance(0);

			String[] dbName = i.getDatabaseNames();

			assertTrue( dbName.length == 2 );
			assertTrue( dbName[0].equals("testdb") );
			assertTrue( dbName[1].equals("testdb2") );

			gsc.close();
		}
		catch (ForestToolException e)
		{
			System.out.println(e.getMessage());
			fail();
		}
	}

	public static void main(String[] args)
	{
		try {
			Class.forName("org.postgresql.Driver");
		}
		catch (Exception e)
		{
			System.out.println(e.getMessage());
			System.exit(-1);
		}

		junit.textui.TestRunner.run(TestInstance.class);
	}
}
