package org.jboss.test.testbeancluster.test;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.io.File;
import java.io.IOException;

import junit.extensions.TestSetup;
import junit.framework.Test;

/** A TestSetup that starts hypersonic before the testcase with a tcp
 * listening port at 1701.
 * 
 * @author Scott.Stark@jboss.org
 * @version $Revison:$
 */
public class DBSetup extends TestSetup
{
   public DBSetup(Test test)
   {
      super(test);
   }

   protected void setUp() throws Exception
   {
         File hypersoniDir = new File("output/hypersonic");
         if (!hypersoniDir.exists())
         {
            hypersoniDir.mkdirs();
         }

         if (!hypersoniDir.isDirectory())
         {
            throw new IOException("Failed to create directory: " + hypersoniDir);
         }
      
         final File dbPath = new File(hypersoniDir, "cif-db");

         // Start DB in new thread, or else it will block us
         Thread serverThread = new Thread("hypersonic")
         {
            public void run()
            {
               try
               {
                  // Create startup arguments
                  String[] args = {
                        "-database",
                        dbPath.toString(),
                        "-port",
                        String.valueOf(1701),
                        "-silent",
                        "false",
                        "-trace",
                        "false",
                        "-no_system_exit",
                        "true",
                   };
                  System.out.println("Starting hsqldb");
                  org.hsqldb.Server.main(args);
                  System.out.println("Done");
               }
               catch (Exception e)
               {
                  e.printStackTrace();
               }
            }
         };
         serverThread.start();
   }

   protected void tearDown() throws Exception
   {
      Class.forName("org.hsqldb.jdbcDriver");
      String dbURL = "jdbc:hsqldb:hsql://localhost:1701";
      Connection conn = DriverManager.getConnection(dbURL, "sa", "");
      Statement statement = conn.createStatement();      
      statement.executeQuery("SHUTDOWN COMPACT");
      
   }

   public static void main(String[] args) throws Exception
   {
      DBSetup setup = new DBSetup(null);
      setup.setUp();
      Thread.sleep(120*1000);
      setup.tearDown();
   }
}
