/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: 
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jtests.util;

import java.lang.reflect.Constructor;
import java.rmi.RemoteException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;
import junit.extensions.RepeatedTest;
//import org.objectweb.jonas.adm.AdmInterface;
import org.objectweb.jonas.jtests.ftables.DBEnv;
import org.objectweb.jonas.jtests.ftables.DBEnvHome;

/**
 * JTestCase extends TestCase to provide a set of standard routines
 * used in jonas tests.
 */
public abstract class JTestCase extends TestCase {
    protected static String jonasName = "jonas"; // change this XXX
    protected static String testtorun = null;
    protected static Context ictx = null;
    public static UserTransaction utx = null;
    //private static AdmInterface admI = null;
    private static DBEnv dbEnv = null;
    private static boolean tableSessionLoaded = false;

    protected StringBuffer msgerror = null;

    public static final String PACKAGE = "org.objectweb.jonas.jtests.clients.";

    public JTestCase(String name) {
        super(name);
    }

    protected static void callTest(String classname, String testname) throws Exception {
        Class clazz = Class.forName(PACKAGE + classname);
        Class[] paramTypes = {String.class};
        Object[] arguments = {testname};
        Constructor constructor = clazz.getDeclaredConstructor(paramTypes);
        JTestCase mytestcase = (JTestCase) constructor.newInstance(arguments);
        //        System.out.print("Running " + classname + " (" + testname + ")\t");
        junit.textui.TestRunner.run(mytestcase);
    }

     protected static void callrepeatedTest(String classname, String testname, int n) throws Exception {
        Class clazz = Class.forName(PACKAGE + classname);
        Class[] paramTypes = {String.class};
        Object[] arguments = {testname};
        Constructor constructor = clazz.getDeclaredConstructor(paramTypes);
        JTestCase mytestcase = (JTestCase) constructor.newInstance(arguments);
        RepeatedTest myrepeatedtest = new RepeatedTest(mytestcase,n);
        //System.out.print("Running repeated " + n + "times " + classname + " (" + testname + ")\t");
        junit.textui.TestRunner.run(myrepeatedtest);
    }

    /**
     * random returns an integer between 0 and max - 1
     */
    public int random(int max) throws RemoteException {
        double d = Math.random();
        int ret = (int) (max * d);
        return ret;
    }

    private Context getInitialContext() throws NamingException {

        String registryPort = System.getProperty("jonas.registryport");
        return new InitialContext();
    }

    /**
     * common setUp routine, used for every test.
     */
    protected void setUp() {
        try {
            // get InitialContext
            if (ictx == null) {
                ictx = getInitialContext();
            }

            // get UserTransaction
            if (utx == null) {
                utx = (UserTransaction) PortableRemoteObject.narrow(ictx.lookup("javax.transaction.UserTransaction"), UserTransaction.class);
            }

            /**
            Load Session bean tables.jar

            if (!tableSessionLoaded) {
                if (admI == null) {
                    admI = (AdmInterface) ictx.lookup(jonasName + "_Adm");
                }
                String filename = "ftables";
                if (!admI.isLoaded(filename + ".jar")) {
                    admI.addBeans(filename + ".jar");
                }
                tableSessionLoaded = true;
            }
             */
        } catch (NamingException e) {
            System.err.println("Cannot setup test: " + e);
            e.printStackTrace();
             /**
        } catch (RemoteException e) {
            System.err.println("Cannot load session bean: " + e);
             */
 }

        debug("Junit Running " + getName());
    }

    protected void tearDown() throws Exception {
    }


    
    public void unloadBeans(String filename) {
        debug("unloadBeans " + filename);

    /**
     * unload a bean

        try {
            // Load bean in EJBServer if not already loaded.
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) ictx.lookup(jonasName + "_Adm");
            }
            admI.removeBeans(filename + ".jar");
        } catch (Exception e) {
            System.err.println("Cannot unload bean: " + e);
        }

        */

    }
    


   
    public void sync(boolean passivate) {
        debug("sync");

    /**
     * synchronize all entity beans
     * @param passivate passivate all instances after synchronization.

        try {
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) ictx.lookup(jonasName + "_Adm");
            }
            admI.syncAllEntities(passivate);
        } catch (Exception e) {
            error("Cannot sync entities" + e);
        }
       */
    }
     

    public void useBeans(String filename, boolean create) {
        debug("useBeans " + filename);


    /**
     * load a bean jar file in the jonas server
     * @param filename jar file, without ".jar" extension
     * @param create creates tables at loading (CMP1 only)
     * Note that in CMP2, the decision to create the tables is in
     * the jonas specific deployment descriptor.
   

        try {
            // Load bean in EJBServer if not already loaded.
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) ictx.lookup(jonasName + "_Adm");
            }
            if (!admI.isLoaded(filename + ".jar")) {
                admI.addBeans(filename + ".jar");

                // Create table if the bean was not loaded
                if (create) {
                    getDBEnv().initTable(filename);
                }
            }
        } catch (Exception e) {
            error("Cannot load bean: " + e);
        }

       */
    }

    /**
     * Get the session bean to manage database tables.
     */
    public DBEnv getDBEnv() {
        if (dbEnv == null) {

            useBeans("ftables", false);

            // Connect to the DBEnvHome object
            DBEnvHome dbhome = null;
            try {
                dbhome = (DBEnvHome) PortableRemoteObject.narrow(ictx.lookup("ftablesDBEnvHome"), DBEnvHome.class);
            } catch (NamingException e) {
                System.err.println(">>> " + e);
                fail("Cannot bind to DBEnvHome");
            }

            // Create the table using a session bean 
            try {
                dbEnv = dbhome.create();
            } catch (Exception e) {
                fail(e.toString());
            }
        }
        return dbEnv;
    }

    /**
     * for debugging : Uncomment the line.
     */
    public static void debug(String msg) {
        //        System.out.println("DEBUG: " + msg);
    }

    /**
     * Print error message.
     */
    public static void error(String msg) {
        System.err.println("ERROR: " + msg);
    }

    /**
     * sleep n millisec.
     */
    public void sleep(int msec) {
        try {
            Thread.currentThread().sleep(msec);
        } catch (InterruptedException e) {
            fail(e.toString());
        }
    }

    public void testEmpty() throws Exception {
    }
}
