/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2005 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
 *
 * Initial developer: JOnAS Team
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.alarm.beans;

import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.SQLException;
import java.sql.Statement;

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 javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 *
 */
public class AlarmRecordBean implements EntityBean {

    EntityContext ejbContext;

    // ------------------------------------------------------------------
    // State of the bean.
    // They must be public for Container Managed Persistance.
    // ------------------------------------------------------------------
    public String pk;

    public int sev;

    public String from;

    public String reason;

    public int count;

    public int state;

    public Date date;

    // ------------------------------------------------------------------
    // init DataBase
    // ------------------------------------------------------------------
    private void initDB() {

        // Get my DataSource from JNDI
        DataSource ds = null;
        InitialContext ictx = null;
        try {
            ictx = new InitialContext();
        } catch (Exception e) {
            throw new EJBException("Cannot get JNDI InitialContext");
        }
        try {
            ds = (DataSource) ictx.lookup("java:comp/env/jdbc/myDS");
        } catch (Exception e) {
            throw new EJBException("cannot lookup datasource");
        }

        // Drop table
        Connection conn = null;
        Statement stmt = null;
        String myTable = "AlarmTable";
        try {
            conn = ds.getConnection();
            stmt = conn.createStatement();
            stmt.execute("drop table " + myTable);
            stmt.close();
        } catch (SQLException e) {
            // The first time, table will not exist.
        }

        // Create table.
        try {
            stmt = conn.createStatement();
            stmt
                    .execute("create table "
                            + myTable
                            + "(dbpk varchar(12) not null primary key, dbsev integer, dbfrom varchar(12), dbreason varchar(30), dbcount integer, dbstate integer, dbdate date)");
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            throw new EJBException("Exception in createTable");
        }
    }

    // ------------------------------------------------------------------
    // 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) {
        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() {
        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 {
    }

    /**
     * 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() {
    }

    /**
     * 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() {
    }

    /**
     * There must be an ejbPostCreate par ejbCreate method
     * @throws CreateException Failure to create an entity EJB object.
     */
    public void ejbPostCreate(AlarmData ad) throws CreateException {
    }

    public void ejbPostCreate() throws CreateException {
    }

    /**
     * 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 String ejbCreate(AlarmData ad) throws CreateException, DuplicateKeyException {

        // Init here the bean fields
        Integer i = new Integer(ad.getNum());
        pk = i.toString();
        sev = ad.getSev();
        from = ad.getDevice();
        reason = ad.getMessage();
        count = 1;
        state = 1;
        date = (java.sql.Date) ad.getDate();

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

    public String ejbCreate() throws CreateException, DuplicateKeyException {

        // init database
        initDB();

        // init bean fields
        pk = "0";
        sev = 99; // avoids taking this as a true AlarmRecord.
        from = "init";
        reason = "init";
        count = 0;
        state = 0;
        date = null;

        // 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() {
    }

    /**
     * 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() {
    }

    // ------------------------------------------------------------------
    // AlarmRecord implementation
    // ------------------------------------------------------------------

    /**
     *
     */
    public void update(int s) {
        count++;
        if (s < sev) {
            sev = s;
        }
        java.util.Date now = new java.util.Date();
        date = new java.sql.Date(now.getTime());
    }

    /**
     * forget
     */
    public void forget() {
        state = 3;
    }

    /**
     * setProcessed
     */
    public void setProcessed() {
        state = 2;
    }

    public String getFrom() {
        return from;
    }

    public int getSeverity() {
        return sev;
    }

    public int getCount() {
        return count;
    }

    /**
     * Get the number of alarms in database only valid for special "0" element.
     */
    public int getAlarmCount() throws RemoteException {
        if (!pk.equals("0")) {
            throw new RemoteException("pk should be 0");
        }
        return count;
    }

    /**
     * Get a new Ident only valid for special "0" element.
     */
    public int getNewIdent() throws RemoteException {
        if (!pk.equals("0")) {
            throw new RemoteException("pk should be 0");
        }
        return ++count;
    }

    /**
     * Returns the AlarmData for that instance
     */
    public AlarmData getAlarmData() throws RemoteException {
        Integer id = new Integer(pk);
        AlarmData ret = new AlarmData(id.intValue(), sev, from, reason, date);
        ret.setCount(count);
        ret.setState(state);
        return ret;
    }
}
