// BankSessionSLR.java
// Stateless Session bean

package org.objectweb.clusterDemo;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.ejb.EJBObject;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import java.util.Vector;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;


/**
 *
 */
public class BankSessionSLR implements SessionBean {

    static private Logger logger = null;
    SessionContext ejbContext;
    
    InitialContext ic = null;
    private DataSource dataSource = null;
    Connection         conn       = null;
    Statement          stmt;

    // ------------------------------------------------------------------
    // SessionBean implementation
    // ------------------------------------------------------------------

    /** 
     * Set the associated session context. The container calls this method
     * after the instance creation. 
     * The enterprise Bean instance should store the reference to the context
     * object in an instance variable. 
     * This method is called with no transaction context.
     *
     * @param sessionContext A SessionContext interface for the instance.
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void setSessionContext(SessionContext ctx) {
        if (logger == null) {
	    logger = Log.getLogger("org.objectweb.jonas_tests");
	}
	logger.log(BasicLevel.DEBUG, "");
	ejbContext = ctx;
    }
	
    /**
     * A container invokes this method before it ends the life of the session object. 
     * This happens as a result of a client's invoking a remove operation, or when a 
     *  container decides to terminate the session object after a timeout. 
     * This method is called with no transaction context. 
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void ejbRemove() {
	logger.log(BasicLevel.DEBUG, "");
    }
	
    /**
     * The Session bean must define 1 or more ejbCreate methods.
     *
     * @throws CreateException Failure to create a session EJB object.
     */
    public void ejbCreate() throws CreateException {
	logger.log(BasicLevel.DEBUG, "");
	try {
            ic = new InitialContext();
        } catch (Exception e) {
            e.printStackTrace();
        }  
    }


    /**
     * A container invokes this method on an instance before the instance
     * becomes disassociated with a specific EJB object.
     */
    public void ejbPassivate() {
	logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * A container invokes this method when the instance is taken out of 
     * the pool of available instances to become associated with a specific 
     * EJB object.
     */
    public void ejbActivate() {
	logger.log(BasicLevel.DEBUG, "");
    }
    
    // ------------------------------------------------------------------
    // BankSession implementation
    // ------------------------------------------------------------------

    /**
     * credit method
     */
    public void credit(Integer accountId, String clientName, int value, String reason) {
	try {
	    logger.log(BasicLevel.DEBUG, "");
	    BankAccountLocalHome accountHome = (BankAccountLocalHome)ic.lookup("java:comp/env/ejb/account");
	    BankAccountLocal account = (BankAccountLocal)accountHome.findByPrimaryKey(accountId);
	    account.putMoney(value);
	    BankOperationLocalHome operationHome = (BankOperationLocalHome)ic.lookup("java:comp/env/ejb/operation");
	    operationHome.create(value, reason+ " in bank " + getBank(), getDate());
	    System.out.println(">>>>>> account " + clientName + " credited");
	} catch (Exception e) {
	    e.printStackTrace();
	}

    }

    /**
     * debit method
     */
    public void debit(Integer accountId, String clientName, int value, String reason) {
	try {
	    logger.log(BasicLevel.DEBUG, ""); 
	    BankAccountLocalHome accountHome = (BankAccountLocalHome)ic.lookup("java:comp/env/ejb/account");
	    BankAccountLocal account = (BankAccountLocal)accountHome.findByPrimaryKey(accountId);
	    account.getMoney(value);
	    BankOperationLocalHome operationHome = (BankOperationLocalHome)ic.lookup("java:comp/env/ejb/operation");
	    operationHome.create(value, reason + " in bank " + getBank(), getDate());
	    System.out.println(">>>>>> account " + clientName + " debited");
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * create new account 
     */
    public Integer createAccount(String clientName, int value) {
	Integer accountId = null;
	try {
	    logger.log(BasicLevel.DEBUG, "");
	    BankAccountLocalHome accountHome = (BankAccountLocalHome)ic.lookup("java:comp/env/ejb/account");
	    BankAccountLocal account = accountHome.create(value,clientName);
	    System.out.println(">>>>>> account " + clientName + " created");
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return accountId;
    }


    /**
     * get Date method for primary key generation
     */
    public String getDate() {
	Calendar c = new GregorianCalendar();
	String result = c.get(Calendar.YEAR) + "/" +
	    c.get(Calendar.MONTH) + "/" +
	    c.get(Calendar.DAY_OF_MONTH) + " ";
	int hour = c.get(Calendar.HOUR_OF_DAY);
	if (hour < 10) {  
	    result += "0"+hour+"h";
	} else {
	    result += ""+hour+"h";	    
	}
	int minute = c.get(Calendar.MINUTE);
	if (minute < 10) {
	    
	    result += "0"+minute+"m";
	} else {
	    result += ""+minute+"m";
	}

	int second = c.get(Calendar.SECOND);
	if (second < 10) {
	    result += "0"+second+"s";
	} else {	    
	    result += ""+second+"s";
	}	    
	return result + " " + getBank();
    }

    /**
     * get Bank value from env value
     */
    public String getBank() {
	try {
	    return (String)ic.lookup("java:comp/env/bankname");
	} catch (Exception e) {
	    e.printStackTrace();
	    return null;
	}
    }

}
