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

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.resource.spi.work.Work;
import javax.resource.spi.work.WorkEvent;
import javax.resource.spi.work.WorkException;
import javax.resource.spi.work.WorkListener;
import javax.resource.spi.work.WorkManager;

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

/**
 * Worker Implementation.
 * This bean is JONAS specific because it uses the JSessionContext
 * to retrieve the WorkManager.
 * @author Philippe Durieux
 */
public class WorkerSF implements SessionBean, Work, WorkListener {

    private static final long serialVersionUID = 1L;
    private static Logger logger = null;
    private JSessionContext ejbContext;
    private WorkManager workManager;
    private int wcount;
    private int notifyAccepted = 0;
    private int notifyStarted = 0;
    private int notifyRejected = 0;
    private int notifyCompleted = 0;

    // ------------------------------------------------------------------
    // 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 ctx 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(Log.JONAS_TESTS_PREFIX);
        }
        logger.log(BasicLevel.DEBUG, "");
        ejbContext = (JSessionContext) 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, "");
    }

    /**
     * Create a session.
     * @throws CreateException Failure to create a session EJB object.
     */
    public void ejbCreate() throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
        wcount = 0;
    }

    /**
     * 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, "");
    }

    // ------------------------------------------------------------------
    // Work implementation
    // ------------------------------------------------------------------

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

    public void run() {
        logger.log(BasicLevel.DEBUG, "");
        wcount++;
    }

    // ------------------------------------------------------------------
    // Worker implementation
    // ------------------------------------------------------------------

    /**
     * set the count
     */
    public void setwcount(int c) throws RemoteException {
        wcount = c;
    }

    /**
     * get the count
     */
    public int getwcount() throws RemoteException {
        return wcount;
    }

    /**
     * @return the notify-accepted count
     */
    public int getNotifyAccepted() {
        return notifyAccepted;
    }

    /**
     * @return the notify-rejected count
     */
    public int getNotifyRejected() {
        return notifyRejected;
    }

    /**
     * @return the notify-completed count
     */
    public int getNotifyCompleted() {
        return notifyCompleted;
    }

    /**
     * @return the notify-started count
     */
    public int getNotifyStarted() {
        return notifyStarted;
    }

    /**
     * Run n works, synchronously.
     */
    public void doWorks(int n) throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        for (int i = 0; i < n; i++) {
            try {
                getWM().doWork(this);
            } catch (WorkException e) {
                throw new RemoteException("doWork failed:" + e);
            }
        }
    }

    /**
     * Start n works
     */
    public void startWorks(int n) throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        for (int i = 0; i < n; i++) {
            try {
                getWM().startWork(this);
            } catch (WorkException e) {
                throw new RemoteException("doWork failed:" + e);
            }
        }
    }

    /**
     * Schedule n works
     */
    public void scheduleWorks(int n, long timeout) throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        for (int i = 0; i < n; i++) {
            try {
                getWM().scheduleWork(this, timeout, null, this);
            } catch (WorkException e) {
                throw new RemoteException("doWork failed:" + e);
            }
        }
    }

    /**
     * Run 1 work synchronously in a TX
     * The tx attribute is set as "Required"
     */
    public void doWorkInTx() throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        try {
            getWM().doWork(this);
        } catch (WorkException e) {
            throw new RemoteException("doWork failed:" + e);
        }
    }

    /**
     * Start 1 work in a TX
     * The tx attribute is set as "Required"
     */
    public void startWorkInTx() throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        try {
            getWM().startWork(this);
        } catch (WorkException e) {
            throw new RemoteException("doWork failed:" + e);
        }
    }

    /**
     * Schedule 1 work in a TX
     * The tx attribute is set as "Required"
     */
    public void scheduleWorkInTx() throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        try {
            getWM().scheduleWork(this);
        } catch (WorkException e) {
            throw new RemoteException("doWork failed:" + e);
        }
    }

    // ------------------------------------------------------------------
    // Private Methods
    // ------------------------------------------------------------------

    /**
     * Get the WorkManager
     */
    private WorkManager getWM() {
        if (workManager == null) {
            workManager = ejbContext.getWorkManager();
        }
        return workManager;
    }

    /**
     * sleep n seconds
     * @param n seconds
     */
    private void sleep(int n) {
        try {
            Thread.sleep(1000 * n);
        } catch (InterruptedException e) {
        }
    }

    // ------------------------------------------------------------------------
    // WorkListener implementation
    // ------------------------------------------------------------------------

    public void workAccepted(WorkEvent we) {
        logger.log(BasicLevel.DEBUG, "");
        notifyAccepted++;
    }

    public void workRejected(WorkEvent we) {
        logger.log(BasicLevel.DEBUG, "");
        notifyRejected++;
    }

    public void workStarted(WorkEvent we) {
        logger.log(BasicLevel.DEBUG, "");
        notifyStarted++;
    }

    public void workCompleted(WorkEvent we) {
        logger.log(BasicLevel.DEBUG, "");
        notifyCompleted++;
    }

}
