/*
 * 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.Status;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

import junit.extensions.RepeatedTest;
import junit.framework.TestCase;

import org.objectweb.jonas.adm.AdmInterface;
import org.objectweb.jonas.jtests.tables.DBEnv;
import org.objectweb.jonas.jtests.tables.DBEnvHome;
import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * 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;

    /**
     * logger for tests: jonas_tests
     * See $JONAS_BASE/conf/traceclient.properties
     */
    static protected Logger logger = null;

    protected StringBuffer msgerror = null;

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

    public JTestCase(String name) {
        super(name);
        if (logger == null) {
            logger = Log.getLogger("org.objectweb.jonas_tests");
        }
    }

    /**
     * deprecated. use logger instead.
     */
    protected void debug(String txt) {
        logger.log(BasicLevel.DEBUG, getName() + ": " + txt);
    }

    /**
     * deprecated. use logger instead.
     */
    protected void error(String txt) {
        logger.log(BasicLevel.ERROR, getName() + ": " + txt);
    }

    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("java:comp/UserTransaction"), UserTransaction.class);
            }
            // get admin interface
            if (admI == null) {
                admI = (AdmInterface) PortableRemoteObject.narrow(ictx.lookup(jonasName + "_Adm"), AdmInterface.class);
            }
        } catch (NamingException e) {
            throw new RuntimeException("Cannot get initial context", e);
        }

        try {
            // rollback transaction if previous test failed to do so
            if (utx.getStatus() != Status.STATUS_NO_TRANSACTION) {
                utx.rollback();
            }
        } catch (SystemException e) {
            throw new RuntimeException("Cannot use UserTransaction", e);
        }

        try {
            // Load Session bean tables.jar
            if (!tableSessionLoaded) {
                String filename = "tables";
                if (!admI.isLoaded(filename + ".jar")) {
                    admI.addBeans(filename + ".jar");
                }
                tableSessionLoaded = true;
            }
        } catch (RemoteException e) {
            throw new RuntimeException("Cannot load tables", e);
        }
        logger.log(BasicLevel.INFO, "Junit Running " + getName());
    }

    protected void tearDown() throws Exception {
        logger.log(BasicLevel.DEBUG, "Junit Stopping " + getName());
    }

    /**
     * unload a bean
     */
    public void unloadBeans(String filename) {
        logger.log(BasicLevel.DEBUG, "unloadBeans " + filename);
        try {
            // Load bean in EJBServer if not already loaded.
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) PortableRemoteObject.narrow(ictx.lookup(jonasName + "_Adm"), AdmInterface.class);
            }
            admI.removeBeans(filename + ".jar");
        } catch (Exception e) {
            System.err.println("Cannot unload bean: " + e);
        }
    }

    /**
     * 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.
     * @return true if bean has just been loaded.
     */
    public boolean useBeans(String filename, boolean create) {
        boolean added = false;
        try {
            // Load bean in EJBServer if not already loaded.
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) PortableRemoteObject.narrow(ictx.lookup(jonasName + "_Adm"), AdmInterface.class);
            }
            if (!admI.isLoaded(filename + ".jar")) {
                logger.log(BasicLevel.INFO, "load beans " + filename);
                admI.addBeans(filename + ".jar");

                // Create table if the bean was not loaded
                if (create) {
                    getDBEnv().initTable(filename);
                }
                added = true;
            }
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "Cannot load bean :" + e);
        }
        return added;
    }

    /**
     * synchronize all entity beans
     * @param passivate passivate all instances after synchronization.
     */
    public void sync(boolean passivate) {
        logger.log(BasicLevel.DEBUG, "sync");
        try {
            if (ictx == null) {
                ictx = getInitialContext();
            }
            if (admI == null) {
                admI = (AdmInterface) PortableRemoteObject.narrow(ictx.lookup(jonasName + "_Adm"), AdmInterface.class);
            }
            if (passivate) {
                sleep(2500);
            }
            admI.syncAllEntities(passivate);
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "Cannot sync entities :" + e);
        }
    }

    /**
     * Set the Default Transaction Timeout value on the server.
     * @param tt timeout in seconds
     */
    public static void stopTxAt(int tt) {
        try {
            if (admI == null) {
                admI = (AdmInterface) PortableRemoteObject.narrow(ictx.lookup(jonasName + "_Adm"), AdmInterface.class);
            }
            admI.setTransactionTimeout(tt);
        } catch (Exception e) {
            System.err.println("Cannot set transaction timeout: " + e);
        }
    }

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

            useBeans("tables", false);

            // Connect to the DBEnvHome object
            DBEnvHome dbhome = null;
            try {
                dbhome = (DBEnvHome) PortableRemoteObject.narrow(ictx.lookup("tablesDBEnvHome"), 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;
    }

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

    public void testEmpty() throws Exception {
    }

}
