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

import java.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.RemoveException;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerHandle;
import javax.ejb.TimerService;

import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Entity bean with container managed persistence version 2.
 * @author Helene Joanin
 */
public abstract class SimpleEC2 extends SimpleCommon implements EntityBean, TimedObject {

    private final int TOCANCEL = 10000;

    protected EntityContext entityContext;

    // ------------------------------------------------------------------
    // Get and Set accessor methods of the bean's abstract schema
    // ------------------------------------------------------------------
    public abstract String getAccno();
    public abstract void setAccno(String accno);
    public abstract String getCustomer();
    public abstract void setCustomer(String customer);
    public abstract long getBalance();
    public abstract void setBalance(long balance);
    public abstract int getTimerIdent();
    public abstract void setTimerIdent(int id);
    public abstract int getTimerCount();
    public abstract void setTimerCount(int cnt);

    /**
     * Create without arg
     * transaction attribute = supports (by default in xml file)
     */
    public String ejbCreate() throws CreateException {

        logger.log(BasicLevel.DEBUG, "");

        // Must init fields in any case.
        setAccno("000");
        setCustomer("Initial");
        setBalance(0);
        setTimerIdent(0);
        setTimerCount(0);
        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = default (= supports)
     */
    public void ejbPostCreate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * transaction attribute = notsupported
     */
    public String ejbCreate(int i) throws CreateException  {

        logger.log(BasicLevel.DEBUG, "");

        if (isAssociated()) {
            throw new EJBException("ejbCreate(int i): should not be in a transaction");
        }
        Integer v = new Integer((int)i);
        setAccno(v.toString());
        setCustomer("by int");
        setBalance(1000 + i);
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = notsupported
     */
    public void ejbPostCreate(int i) {
        logger.log(BasicLevel.DEBUG, "");
        if (isAssociated()) {
            throw new EJBException("ejbPostCreate(int i): should not be in a transaction");
        }
    }

    /**
     * transaction attribute = required
     */
    public String ejbCreateForRequired(long i)  throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
        if (!isAssociated()) {
            throw new EJBException("ejbCreate(long i): should be in a transaction");
        }
        Integer v = new Integer((int)i);
        setAccno(v.toString());
        setCustomer("Required");
        setBalance(1000 + i);
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = required
     */
    public void ejbPostCreateForRequired(long i) {
        logger.log(BasicLevel.DEBUG, "");
        if (!isAssociated()) {
            throw new EJBException("ejbPostCreateForRequired(long i): should be in a transaction");
        }
    }

    /**
     * transaction attribute = never
     */
    public String ejbCreateForNever(short i)  throws CreateException {
        logger.log(BasicLevel.DEBUG, "");

        if (isAssociated()) {
            throw new EJBException("ejbCreateForNever(short i): should not be in a transaction");
        }
        Integer v = new Integer((int)i);
        setAccno(v.toString());
        setCustomer("by short");
        setBalance(1000 + i);
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = requiresnew
     */
    public String ejbCreateForRequiresNew(String i)  throws CreateException {
        logger.log(BasicLevel.DEBUG, "");

        if (!isAssociated()) {
            throw new EJBException("ejbCreate(String i): should be in a transaction");
        }
        setAccno(i);
        setCustomer("by string");
        setBalance(100);
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = requiresnew
     */
    public void ejbPostCreateForRequiresNew(String i) {
        logger.log(BasicLevel.DEBUG, "");

        if (!isAssociated()) {
            throw new EJBException("ejbPostCreateForRequiresNew(String i): should be in a transaction");
        }
    }

    /**
     * transaction attribute = mandatory
     */
    public String ejbCreateForMandatory(char i)  throws CreateException {
        logger.log(BasicLevel.DEBUG, "");

        if (!isAssociated()) {
            throw new EJBException("ejbCreateForMandatory(char i): should be in a transaction");
        }
        Integer v = new Integer((int)i);
        setAccno(v.toString());
        setCustomer("by char");
        setBalance(200);
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = mandatory
     */
    public void ejbPostCreateForMandatory(char i) {
        logger.log(BasicLevel.DEBUG, "");

        if (!isAssociated()) {
            throw new EJBException("ejbPostCreateForMandatory(char i): should be in a transaction");
        }
    }

    /**
     * transaction attribute = supports
     */
    public String ejbCreateForSupports(boolean intx)  throws CreateException {
        logger.log(BasicLevel.DEBUG, "");

        if (intx) {
            setAccno("TRUE");
            setBalance(101);
            if (!isAssociated()) {
                throw new EJBException("ejbCreateForSupports(true): should be in a transaction");
            }
        } else {
            setAccno("FALSE");
            setBalance(102);
            if (isAssociated()) {
                throw new EJBException("ejbCreate(false): should not be in a transaction");
            }
        }
        setCustomer("by boolean");
        setTimerIdent(0);
        setTimerCount(0);

        // In BMP, return PK.
        return getAccno();
    }

    /**
     * transaction attribute = supports
     */
    public void ejbPostCreateForSupports(boolean intx) {
        logger.log(BasicLevel.DEBUG, "");

        if (intx) {
            if (!isAssociated()) {
                throw new EJBException("ejbPostCreateForSupports: should be in a transaction");
            }
        } else {
            if (isAssociated()) {
                throw new EJBException("ejbPostCreateForSupports: should not be in a transaction");
            }
        }
    }

    public String ejbCreateWithTimer(int i, long dur) throws RemoteException, CreateException {
        logger.log(BasicLevel.DEBUG, "");
        // Must init fields in any case.
        setAccno("001");
        setCustomer("Timer");
        setBalance(0);
        setTimerIdent(0);
        setTimerCount(0);
        // In BMP, return PK.
        return getAccno();
    }

    public void ejbPostCreateWithTimer(int i, long dur) throws RemoteException, CreateException {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        int ret = getTimerIdent() + 1;
        Timer mt = timerservice.createTimer(dur, new Integer(ret));
    }

    /**
     * transaction attribute = never
     */
    public void ejbPostCreateForNever(short i) {
        logger.log(BasicLevel.DEBUG, "");

        if (isAssociated()) {
            throw new EJBException("ejbPostCreateForNever(short i): should not be in a transaction");
        }
    }


    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean  ejbHomeOpwith_notsupported() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean ejbHomeOpwith_supports() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean  ejbHomeOpwith_required() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean ejbHomeOpwith_requires_new() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean ejbHomeOpwith_mandatory() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    /**
     * This method return true if there is an association of a transaction with this thread
     */
    public boolean ejbHomeOpwith_never() {
        logger.log(BasicLevel.DEBUG, "");
        return isAssociated();
    }

    public void ejbRemove() throws RemoveException {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbPassivate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbLoad() {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void ejbStore() {
        logger.log(BasicLevel.DEBUG, "");
    }

    public void setEntityContext(EntityContext ctx) {
    	setEjbContext(ctx);
        initLogger();
        logger.log(BasicLevel.DEBUG, "");
        this.entityContext = ctx;
    }

    public void unsetEntityContext() {
        logger.log(BasicLevel.DEBUG, "");
        this.entityContext = null;
    }

    public int setTimer(int dur, int period) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Timer mt = null;
        int ret = getTimerIdent() + 1;
        setTimerIdent(ret);
        if (period > 0) {
            mt = timerservice.createTimer(dur * 1000, period * 1000, new Integer(ret));
        } else if (period < 0) {
            // special test for cancel inside ejbTimeout
            mt = timerservice.createTimer(dur * 1000, -period * 1000, new Integer(TOCANCEL));
        } else {
            mt = timerservice.createTimer(dur * 1000, new Integer(ret));
        }
        return ret;
    }

    public int setTimer(java.util.Date date, int period) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Timer mt = null;
        int ret = getTimerIdent() + 1;
        setTimerIdent(ret);
        if (period > 0) {
            mt = timerservice.createTimer(date, period * 1000, new Integer(ret));
        } else if (period < 0) {
            // special test for cancel inside ejbTimeout
            mt = timerservice.createTimer(date, -period * 1000, new Integer(TOCANCEL));
        } else {
            mt = timerservice.createTimer(date, new Integer(ret));
        }
        return ret;
    }

    public int setTimerGetHandle(int dur, int period) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        int ret = dur * 10 + period;
        Timer t = null;
        if (period > 0) {
            t = timerservice.createTimer(dur * 1000, period * 1000, new Integer(ret));
        } else {
            t = timerservice.createTimer(dur * 1000, new Integer(ret));
        }
        TimerHandle hdl = t.getHandle();
        Timer t2 = hdl.getTimer();
        if (t != t2) {
            logger.log(BasicLevel.ERROR, "Bad timer handle");
            logger.log(BasicLevel.ERROR, "Original=" + t);
            logger.log(BasicLevel.ERROR, "Recomputed=" + t2);
            throw new EJBException("Bad timer handle");
        }
        return ret;
    }

    public TimerHandle getTimerHandle(int ident) {
        logger.log(BasicLevel.DEBUG, "");
        TimerHandle hdl = null;
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        for (Iterator i = timerList.iterator(); i.hasNext(); ) {
            Timer t = (Timer) i.next();
            Integer id = (Integer) t.getInfo();
            if (id.intValue() == ident) {
                hdl = t.getHandle();
                break;
            }
        }
        return hdl;
    }

    public void cancelTimer(int ident) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        for (Iterator i = timerList.iterator(); i.hasNext(); ) {
            Timer t = (Timer) i.next();
            Integer id = (Integer) t.getInfo();
            if (id.intValue() == ident) {
                t.cancel();
            }
        }
    }

    public void cancelTimers() {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        for (Iterator i = timerList.iterator(); i.hasNext(); ) {
            Timer t = (Timer) i.next();
            t.cancel();
        }
    }

    public long getTimeRemaining(int ident) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        long ret = -1;
        for (Iterator i = timerList.iterator(); i.hasNext(); ) {
            Timer t = (Timer) i.next();
            Integer id = (Integer) t.getInfo();
            if (id.intValue() == ident) {
                ret = t.getTimeRemaining();
            }
        }
        return ret;
    }

    public int getTimerNumber() {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        return timerList.size();
    }

    /**
     * This support method calls a required method
     */
    public boolean supports_call_required() throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        Simple myentity = (Simple) entityContext.getEJBLocalObject();
        return myentity.opwith_required();
    }

    /**
      * Cancels all timers, that are associated with this entity, and starts a
      * new timer.
      */
    public void startInfoTimer(int dur, String inform) throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        // Remove all timers with this Info first
        for (Iterator timers = timerservice.getTimers().iterator(); timers.hasNext();) {
            Timer timer = (Timer) timers.next();
            if (inform.equals(timer.getInfo())) {
                timer.cancel();
            }
        }
        // Now, create the Timer
        timerservice.createTimer(dur * 1000, inform);
    }

    // -----------------------------------------------------------
    // TimedObject implementation
    // -----------------------------------------------------------

    /**
     * A timer is expired.
     */
    public void ejbTimeout(Timer timer) {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = entityContext.getTimerService();
        Collection timerList = timerservice.getTimers();
        Integer id = (Integer) timer.getInfo();
        if (id.intValue() == TOCANCEL) {
            timer.cancel();
        }
        setTimerCount(getTimerCount() + 1);
        TimerHandle hdl = timer.getHandle();
        TimerHandle hdl2 = getDeserializedHandle(hdl);
        if (! timersAreIdentical(hdl, hdl2)) {
            logger.log(BasicLevel.ERROR, "Bad timer handle");
            throw new EJBException("Bad timer handle");
        }
    }
}
