/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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 lb;

import java.rmi.RemoteException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Client of the lb JOnAS example
 * @author Helene Joanin
 */
public class Client {

    static Context initialContext = null;

    static ManagerHome home = null;

    static Manager manager = null;

    static boolean m_noinit = false;

    static int m_accounts = 4;

    static int m_valmove = 100;

    static int m_loops = 10;

    static int inival = 1000;

    public static void main(String[] args) {

        // Get command args
        for (int argn = 0; argn < args.length; argn++) {
            String s_arg = args[argn];
            Integer i_arg;
            if (s_arg.equals("-ni")) {
                m_noinit = true;
            } else if (s_arg.equals("-a")) {
                s_arg = args[++argn];
                i_arg = java.lang.Integer.valueOf(s_arg);
                m_accounts = i_arg.intValue();
            } else if (s_arg.equals("-m")) {
                s_arg = args[++argn];
                i_arg = java.lang.Integer.valueOf(s_arg);
                m_valmove = i_arg.intValue();
            } else if (s_arg.equals("-l")) {
                s_arg = args[++argn];
                i_arg = java.lang.Integer.valueOf(s_arg);
                m_loops = i_arg.intValue();
            } else {
                usage();
                fatalError("wrong usage");
            }
        }

        info("Calling lb.Client with : -a " + m_accounts + " -m " + m_valmove + " -l " + m_loops);

        // Get InitialContext
        try {
            initialContext = new InitialContext();
        } catch (NamingException e) {
            fatalError("Cannot get InitialContext: " + e);
        }

        // Create manager session bean
        try {
            home = (ManagerHome) javax.rmi.PortableRemoteObject.narrow(initialContext.lookup("ManagerHome"),
                    ManagerHome.class);
            manager = home.create(inival);
        } catch (Exception e) {
            fatalError("Cannot create manager: " + e);
        }

        // Create all accounts if noinit==false
        if (!m_noinit) {
            info("Re-initialization of the accounts database table");
            try {
                manager.createAll(m_accounts);
            } catch (Exception e) {
                fatalError("Cannot create initial accounts: " + e);
            }
        }

        // Set move value
        try {
            manager.setValue(m_valmove);
        } catch (Exception e) {
            fatalError("Cannot init Session: " + e);
        }

        // main loop
        try {
            for (int i = 0; i < m_loops; i++) {
                // Choose the 2 accounts randomly
                int d1 = random(m_accounts);
                int c1 = random(m_accounts);
                info("  Movement " + d1 + " -> " + c1 + "");
                // Set these accounts in session bean
                manager.setAccounts(d1, c1);
                // make the transfert
                try {
                    manager.movement();
                } catch (RemoteException r) {
                    error("movement raised exception. ignoring...");
                }
                // Check account that was debited
                if (manager.checkAccount(d1) == false) {
                    error("Bad Account after move on account " + d1);
                    error("Stopping this session because some accounts are not ok");
                    break;
                }
            }
        } catch (Exception e) {
            fatalError("Exception in main loop :" + e);
        }

        // Check all accounts
        try {
            if (manager.checkAll() == false) {
                error("FAIL when checking all accounts");
            } else {
                info("PASS when checking all accounts");
            }
        } catch (RemoteException e) {
            error("checkAll() :" + e);
        }

        // remove session bean
        try {
            manager.remove();
        } catch (Exception e) {
            error("Cannot remove manager session: " + e);
        }

    }

    /**
     * Returns an integer between 0 and max-1
     */
    static int random(int max) {

        double d = Math.random();
        int ret = (int) (max * d);
        return ret;
    }

    /**
     * Display the usage
     */
    static void usage() {
        info("lb.Client [-ni] [-a accounts] [-m value] [-l loops]");
    }

    /**
     * Display the given information message
     */
    static void info(String infoMsg) {
        System.out.println(infoMsg);
    }

    /**
     * Display the given error message
     */
    static void error(String errMsg) {
        System.out.println("lb.Client error: " + errMsg);
    }

    /**
     * Display the given error message and exits
     */
    static void fatalError(String errMsg) {
        System.out.println("lb.Client fatal error: " + errMsg);
        System.exit(2);
    }

}

