/*
 * 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.beans.bank;

import javax.ejb.CreateException;
import javax.ejb.DuplicateKeyException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.RemoveException;

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

/**
 * Account Implementation (with container-managed persistence version 2)
 * @author Philippe Durieux
 */
public abstract class AccountEC2 implements EntityBean {

    protected static Logger history = null;
    EntityContext ejbContext;

    // ------------------------------------------------------------------
    // Get and Set accessor methods of the bean's abstract schema
    // ------------------------------------------------------------------
    public abstract String getName();
    public abstract void setName(String n);
    public abstract int getNum();
    public abstract void setNum(int n);
    public abstract int getBalance();
    public abstract void setBalance(int b);

    // ------------------------------------------------------------------
    // EntityBean implementation
    // ------------------------------------------------------------------

    /**
     * Set the associated entity context. The container invokes this method
     * on an instance after the instance has been created.
     * This method is called in an unspecified transaction context.
     *
     * @param ctx - An EntityContext interface for the instance. The instance
     * should store the reference to the context in an instance variable.
     * @throws EJBException Thrown by the method to indicate a failure caused by a
     * system-level error.
     */
    public void setEntityContext(EntityContext ctx) {
        if (history == null) {
            history = Log.getLogger("org.objectweb.jonas_tests.history");
        }
        history.log(BasicLevel.DEBUG, getName());
        ejbContext = ctx;
    }

    /**
     * Unset the associated entity context. The container calls this method
     * before removing the instance.
     * This is the last method that the container invokes on the instance.
     * The Java garbage collector will eventually invoke the finalize() method
     * on the instance.
     * This method is called in an unspecified transaction context.
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by a
     * system-level error.
     */
    public void unsetEntityContext() {
        history.log(BasicLevel.DEBUG, getName());
        ejbContext = null;
    }

    /**
     * A container invokes this method before it removes the EJB object
     * that is currently associated with the instance. This method is
     * invoked when a client invokes a remove operation on the enterprise Bean's
     * home interface or the EJB object's remote interface. This method
     * transitions the instance from the ready state to the pool of available
     * instances.
     *
     * This method is called in the transaction context of the remove operation.
     * @throws RemoveException  The enterprise Bean does not allow destruction of the object.
     * @throws EJBException - Thrown by the method to indicate a failure caused by a system-level
     * error.
     */
    public void ejbRemove() throws RemoveException {
        history.log(BasicLevel.DEBUG, getName());
    }

    /**
     * A container invokes this method to instruct the instance to synchronize
     * its state by loading it state from the underlying database.
     * This method always executes in the proper transaction context.
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void ejbLoad() {
        String name = getName();
        int balance = getBalance();
        history.log(BasicLevel.DEBUG, name + "\tLOAD= " + balance);
        if (balance < 0) {
            history.log(BasicLevel.WARN, name + " : Bad balance loaded");
            throw new EJBException("ejbLoad: Balance "+name+" was negative ="+balance);
        }
    }

    /**
     * A container invokes this method to instruct the instance to synchronize
     * its state by storing it to the underlying database.
     * This method always executes in the proper transaction context.
     *
     * @throws EJBException Thrown by the method to indicate a failure caused by
     * a system-level error.
     */
    public void ejbStore() {
        String name = getName();
        int balance = getBalance();
        history.log(BasicLevel.DEBUG, name + "\tSTORE= " + balance);
        if (balance < 0) {
            history.log(BasicLevel.WARN, name + " : Bad balance stored");
            throw new EJBException("ejbStore: Balance "+name+" was negative ="+balance);
        }
    }

    /**
     * There must be an ejbPostCreate par ejbCreate method
     *
     * @throws CreateException Failure to create an entity EJB object.
     */
    public void ejbPostCreate(int num, int ib) throws CreateException {
        history.log(BasicLevel.DEBUG, getName());
    }

    /**
     * The Entity bean can define 0 or more ejbCreate methods.
     *
     * @throws CreateException Failure to create an entity EJB object.
     * @throws DuplicateKeyException An object with the same key already exists.
     */
    public java.lang.String ejbCreate(int num, int ib) throws CreateException, DuplicateKeyException {

        // Init here the bean fields
        setNum(num);
        setName("a_"+(new Integer(num)).toString());
        setBalance(ib);

        history.log(BasicLevel.DEBUG, getName());

        // In CMP, should return null.
        return null;
    }

    /**
     * A container invokes this method on an instance before the instance
     * becomes disassociated with a specific EJB object.
     */
    public void ejbPassivate() {
        // balance may be wrong in case of rollback. Anyway, this instance is being
        // released now, so no problem!
        // This causes problems (in case of DB policy at least)
        //setBalance(-80000);
        history.log(BasicLevel.DEBUG, getName());
    }

    /**
     * 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() {
        history.log(BasicLevel.DEBUG, getName() + " balance=" + getBalance());
    }

    // ------------------------------------------------------------------
    // Bank implementation
    // ------------------------------------------------------------------

    /**
     * credit
     */
    public void credit(int v) {
        String name = getName();
        if (getBalance() < 0) {
            if (ejbContext.getRollbackOnly() == true) {
                history.log(BasicLevel.WARN, name + " : tx already rollbackonly");
                setBalance(-99000);
                return;
            }
            history.log(BasicLevel.WARN, name + " : Bad balance to credit ="+getBalance());
            throw new EJBException("credit: Balance "+name+" was negative ="+getBalance());
        }
        int oldval = getBalance();
        setBalance(oldval + v);
        history.log(BasicLevel.DEBUG, name + "\told= " + oldval + "\tnew= " + getBalance());
    }

    /**
     * debit
     */
    public void debit(int v) {
        String name = getName();
        int oldval = getBalance();
        if (oldval < 0) {
            if (ejbContext.getRollbackOnly() == true) {
                history.log(BasicLevel.WARN, name + " : tx already rollbackonly");
                setBalance(-99000);
                return;
            }
            history.log(BasicLevel.WARN, name + " : Bad balance to debit="+oldval);
            throw new EJBException("debit: Balance "+name+" was negative ="+oldval);
        }
        setBalance(oldval - v);
        if (getBalance() < 0) {
            history.log(BasicLevel.WARN, name + " : set rollback only. NEW BAL = -90000");
            ejbContext.setRollbackOnly();
            setBalance(-90000);	// put it a very bad balance to check rollback is OK
        }
        history.log(BasicLevel.DEBUG, name + "\tOLD= " + oldval + "\tNEW= " + getBalance());
    }

}
