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

import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.EJBHome;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBMetaData;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.ejb.CreateException;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerHandle;
import javax.ejb.TimerService;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

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

/**
 * Implementation for the bean FileEC.
 * @author Philippe Durieux
 */
public class FileEC implements EntityBean, TimedObject {

    protected static Logger logger = null;
    EntityContext ejbContext;
    InitialContext ictx;
    Context myEnv;
    PaperLocalHome phome;
    PaperLocal p1;
    PaperLocal p2;

    // ------------------------------------------------------------------
    // State of the bean. 
    // They must be public for Container Managed Persistance.
    // ------------------------------------------------------------------
    public String name;
    public String p1pk;
    public String p2pk;
    public int count;

    /**
     * Check environment variables
     */
    void checkEnv(String method) {

        // Check directly in my context
        logger.log(BasicLevel.DEBUG, "Check directly in my context");
        try {
            String value = (String) myEnv.lookup("myname");
            if (!value.equals("myentity")) {
                logger.log(BasicLevel.ERROR, ": myEnv.lookup failed: myname=" + value);
                throw new EJBException("FileEC 1: " + method);
            }
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, ": myEnv.lookup raised exception:\n" + e);
            throw new EJBException("FileEC 2: " + method);
        }
        // Check from initial Context
        logger.log(BasicLevel.DEBUG, "Check from initial Context");
        try {
            String value = (String) ictx.lookup("java:comp/env/myname");
            if (!value.equals("myentity")) {
                logger.log(BasicLevel.ERROR, ": ictx.lookup failed: myname=" + value);
                throw new EJBException("FileEC 6: " + method);
            }
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, ": ictx.lookup raised exception:\n" + e);
            throw new EJBException("FileEC 7: " + method);
        }
        logger.log(BasicLevel.DEBUG, ": checkEnv OK");
    }

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

    /*
     * @param timer the Timer object
     * @see javax.ejb.TimedObject#ejbTimeout(javax.ejb.Timer)
     */
    public void ejbTimeout(Timer timer) {
        logger.log(BasicLevel.DEBUG, "");
        Serializable sz = timer.getInfo();
        if (!(sz instanceof Integer)) {
            logger.log(BasicLevel.ERROR, "Bad Info");
            return;
        }
        int action = ((Integer)sz).intValue();
        boolean ok = true;
    }
    
    // ------------------------------------------------------------------
    // EntityBean implementation
    // ------------------------------------------------------------------

    /**
     * Called by the container after the instance has been created.
     */
    public void setEntityContext(EntityContext ctx) { 
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_TESTS_PREFIX);
        }
        logger.log(BasicLevel.DEBUG, "");
        ejbContext = ctx;
        try {
            // Get initial Context
            ictx = new InitialContext();
            myEnv = (Context) ictx.lookup("java:comp/env");
        } catch (NamingException e) {
            throw new EJBException("FileEC: Cannot get filehome:" + e);
        }
        checkEnv("setEntityContext");

        // Check that we can do "getEJBHome"
        EJBHome home = ctx.getEJBHome();
        if (home == null) {
            throw new EJBException("FileEC: setEntityContext cannot get EJBHome");
        }
        // Check that we can do "getEJBLocalHome"
        EJBLocalHome homel = ctx.getEJBLocalHome();
        if (homel == null) {
            throw new EJBException("FileEC: setEntityContext cannot get EJBLocalHome");
        }
        // Check that we can do "getEJBMetaData"
        try {
            EJBMetaData md = home.getEJBMetaData();
        } catch (RemoteException e) {
            throw new EJBException("FileEC: setEntityContext cannot get EJBMetaData");
        }
    }

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

    public void ejbActivate() {
        logger.log(BasicLevel.DEBUG, "");
        try {
            stateUpdate();
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, "FileEC ejbActivate raised exception " + e);
            throw new EJBException("Error in ejbActivate:" + e);
        }
    }

    public void ejbPassivate() {
        logger.log(BasicLevel.DEBUG, "");
        // raz values to verify that activation is ok.
        phome = null;
        p1 = null;
        p2 = null;
    }

    /**
     * Persistent state has been loaded just before this method is invoked 
     * by the container.
     * Must reinit here non persistent data.
     */
    public void ejbLoad() {
        logger.log(BasicLevel.DEBUG, "");
        p1 = null;
        if (p1pk.length() > 0) {
            try {
                p1 = phome.findByPrimaryKey(p1pk);
            } catch (FinderException e) {
            }
        }
        p2 = null;
        if (p2pk.length() > 0) {
            try {
                p2 = phome.findByPrimaryKey(p2pk);
            } catch (FinderException e) {
            }
        }
    }

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

    // ------------------------------------------------------------------
    // ejbCreate methods
    // ------------------------------------------------------------------

    public String ejbCreate(String name) throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
        this.name = name;
        return null;            // In CMP, should return null.
    }

    public String ejbPostCreate(String name) throws CreateException {
        logger.log(BasicLevel.DEBUG, "");
        try {
            stateUpdate();
        } catch (NamingException e) {
            logger.log(BasicLevel.ERROR, "FileEC ejbPostCreate raised exception " + e);
            throw new CreateException("Error in ejbPostCreate:" + e);
        }
        return null;            // In CMP, should return null.
    }

    // ------------------------------------------------------------------
    // File / FileLocal implementation
    // ------------------------------------------------------------------

    public TimerHandle getTimerHandle() throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        TimerService timerservice = ejbContext.getTimerService();
        Timer mt =  timerservice.createTimer(300 * 1000, new Integer(1));
        TimerHandle th = mt.getHandle();
        return th;
    }

    public void cancelTimer(TimerHandle th) throws RemoteException {
        logger.log(BasicLevel.DEBUG, "");
        Timer mt =  th.getTimer();
        mt.cancel();
    }
    
    public int getP1Value() {
        logger.log(BasicLevel.DEBUG, "");
        int ret = p1.getValue();
        return ret;
    }

    public int getP2Value() {
        logger.log(BasicLevel.DEBUG, "");
        int ret = p2.getValue();
        return ret;
    }

    public String getName() {
        logger.log(BasicLevel.DEBUG, "");
        return this.name;
    }

    public int getCount() {
        logger.log(BasicLevel.DEBUG, "");
        return this.count;
    }

    public PaperLocal getP1() {
        logger.log(BasicLevel.DEBUG, "");
        return p1;
    }

    public PaperLocal getP2() {
        logger.log(BasicLevel.DEBUG, "");
        return p2;
    }

    // ------------------------------------------------------------------
    // private methods
    // ------------------------------------------------------------------

    /**
     * init non persistent bean data.
     * This should be called when instance is created or activated.
     */
    private void stateUpdate() throws NamingException {
        // lookup paperhome in JNDI
        phome = (PaperLocalHome) ictx.lookup("java:comp/env/ejb/paper");
    }

}

