/*
 *
 * Copyright 2000 Sun Microsystems, Inc. All Rights Reserved.
 * 
 * This software is the proprietary information of Sun Microsystems, Inc.  
 * Use is subject to license terms.
 * 
 */

package com.web_tomorrow.item;

import java.sql.*;
import javax.sql.*;
import java.util.*;
import javax.ejb.*;
import javax.naming.*;


public class ItemEJB implements EntityBean {

   // Item Table var
/*   private String cempresa;
   private String cartrefe;*/
   private ItemKey pk = new ItemKey(null,null);
   private String dartrefe;
   private double iartpvpa;

   // Local entitybean var    
   private EntityContext context;
   private Connection con;
   private String dbName = "java:jdbc/OracleDS";//SFDB

    // Getters
    public String getCompanyId() {
       
       return pk.cempresa;
    }
 
    public String getItemId() {
 
       return pk.cartrefe;
    }

    public String getDesc() {

       return dartrefe;
    }
  
    public double getPrice() {

       return iartpvpa;
    }
    
/*    public void debit(double amount) 
       throws InsufficientBalanceException {

       if (balance - amount < 0) {
           throw new InsufficientBalanceException();
       }
       balance -= amount;
    }

    public void credit(double amount) {

       balance += amount;
    }
*/

/*********************** EntityBean interface *************************/
    
   public ItemKey ejbCreate(String companyId, String itemId, String desc, 
       double price)
       throws CreateException {

       if (companyId == null || itemId == null) {
          throw new CreateException("The companyId and itemId are required.");
       }

       if (price < 0.00) {
          throw new CreateException
             ("A negative initial price is not allowed.");
       }

       try {
          insertRow(companyId, itemId, desc, price);
       } catch (Exception ex) {
           EJBLog.logItemEJB("ejbCreate\t Excepcion despues de insertrow***");
       
           try {
              con.close();
              
           } catch (SQLException sqex) {
              throw new EJBException("unsetEntityContext: " + sqex.getMessage());
           } finally  {
              throw new EJBException("ejbCreate: " + 
                 ex.getMessage());
           }  
       }

       this.pk.cempresa = companyId;
       this.pk.cartrefe = itemId;
       this.dartrefe = desc;
       this.iartpvpa = price;
       
       EJBLog.logItemEJB("ejbCreate\t Item="+pk);
       
       return new ItemKey(companyId, itemId);
    }

   public ItemKey ejbFindByPrimaryKey(ItemKey primaryKey) 
      throws FinderException {

      boolean result;
      
      try {
         result = selectByPrimaryKey(primaryKey);
       } catch (Exception ex) {
           throw new EJBException("ejbFindByPrimaryKey: " + 
              ex.getMessage());
       }
      if (result) {
          EJBLog.logItemEJB("ejbFindByPrimaryKey\t Item="+primaryKey);
          return primaryKey;
      }
      else {
         throw new ObjectNotFoundException
            ("Row for " + primaryKey.getCompanyId() + primaryKey.getItemId() + " not found.");
      }
   }

   public Collection ejbFindByItemIdPattern(String itemIdPattern)
      throws FinderException {

      Collection result;
      
      try {
          result = selectByItemIdPattern(itemIdPattern);
      } catch (Exception ex) {
           throw new EJBException("ejbFindByItemIdPattern: " + 
              ex.getMessage());
      }
      
      if (result.isEmpty()) {
          throw new ObjectNotFoundException("No rows found.");
      }
      else {
          EJBLog.logItemEJB("ejbFindByItemIdPattern\t Items gathered "+result.size());
          return result;
      }
   }

   public void ejbRemove() {

      try {
         deleteRow(pk);
         
         EJBLog.logItemEJB("ejbRemove\t Item="+pk);
       } catch (Exception ex) {
           throw new EJBException("ejbRemove" + 
              ex.getMessage());
       }
   } 

   public void setEntityContext(EntityContext context) {

      this.context = context;
      try {
         makeConnection();
         EJBLog.logItemEJB("setEntityContext:Conexion realizada");
      } catch (Exception ex) {
          throw new EJBException("Unable to connect to database. " +
             ex.getMessage());
      }
   }

   public void unsetEntityContext() {

      try {
         con.close();
         EJBLog.logItemEJB("unsetEntityContext:Conexion cerrada Item="+pk+"**********************************");
      } catch (SQLException ex) {
          throw new EJBException("unsetEntityContext: " + ex.getMessage());
      }
   }

   public void ejbActivate() {
      
      pk = (ItemKey)context.getPrimaryKey();

/*      this.cempresa = pk.getCompanyId();
      this.cartrefe = pk.getItemId();*/
      
      EJBLog.logItemEJB("ejbActivate\t Item="+pk);
      
      /* Según la especificación, ejbActivate debe recuperar la primarykey
       * para que cuando el Application Server llame al ejbLoad no de una excepción.
       * Sin embargo, el AS no llama nunca al ejbLoad, así que lo pongo a pelo
       */
      ejbLoad();
   }

   public void ejbPassivate() {

      EJBLog.logItemEJB("ejbPassivate\t Item="+pk+"----------------------------------------------------------");
      
      pk=null;
/*      this.cempresa = null;
      this.cartrefe = null;*/
   }

   public void ejbLoad() {

      try {
         loadRow();
         
         EJBLog.logItemEJB("ejbLoad\t Item="+pk);
       } catch (Exception ex) {
           throw new EJBException("ejbLoad: " + 
              ex.getMessage());
       }
   }
   
   public void ejbStore() {

      try {
         storeRow();
         
         EJBLog.logItemEJB("ejbStore\t Item="+pk);
       } catch (Exception ex) {
           throw new EJBException("ejbStore: " + 
              ex.getMessage());
       }
   }


   public void ejbPostCreate(String companyId, String itemId, String desc, 
       double price) { }


/*********************** Finders *************************/
    
/*   

   public Collection ejbFindInRange(double low, double high)
      throws FinderException {

      Collection result;

      try {
         result = selectInRange(low, high);
            
       } catch (Exception ex) {
           throw new EJBException("ejbFindInRange: " + 
              ex.getMessage());
       }
      if (result.isEmpty()) {
         throw new ObjectNotFoundException("No rows found.");
      }
      else {
         return result;
      }
   }
*/

/*********************** Database Routines *************************/

   private void makeConnection() throws NamingException, SQLException {

      InitialContext ic = new InitialContext();
      DataSource ds = (DataSource) ic.lookup(dbName);
      con =  ds.getConnection();
   }

   private void insertRow (String thecempresa, String thecartrefe, String thedartrefe, 
       double theiartpvpa) throws SQLException {

       String insertStatement = "insert " + 
/*          "T6198000.CEMPRESA, " +
          "T6198000.CARTREFE, " +
          "T6198000.DARTREFE, " +
          "T6198000.DARTCORT, " +
          "T6198000.DARTLIN1, " +
          "T6198000.DARTLIN2, " +
          "T6198000.DARTLIN3, " +
          "T6198000.IARTPVPA, " +
          "T6198000.CDEPARTM, " +
          "T6198000.CGRUPENV, " +
          "T6198000.CVTAREST, " +
          "T6198000.CTIPIMPU, " +
          "T6198000.QUNIDMED, " +
          "T6198000.COFERTAS, " +
          "T6198000.CTIPOFER, " +
          "T6198000.HINICUAR, " +
          "T6198000.HFINCUAR, " +
          "T6198000.IARTPCPF, " +
          "T6198000.QMAXUDTR, " +
          "T6198000.QUDSUMBR, " + //el 20º
          "T6198000.XAPLUMBR, " +
          "T6198000.QUDREGTE, " +
          "T6198000.QUDREGDA, " +
          "T6198000.IPVPLOTE, " +
          "T6198000.QLOTEXTN, " +
          "T6198000.QARTLOTE, " +
          "T6198000.QUDPARTI, " +
          "T6198000.QARTDIST, " +
          "T6198000.CPROMOCI, " +
          "T6198000.XPRECREQ, " +
          "T6198000.XTALLREQ, " +
          "T6198000.XCOLOREQ, " +
          "T6198000.XDIBUREQ, " +
          "T6198000.XDEVNOPE, " +
          "T6198000.XDTONOPE, " +
          "T6198000.XVTANOPE, " +
          "T6198000.XETIMAGN, " +
          "T6198000.XARTREOF, " +
          "T6198000.XEXCGLOB, " +
          "T6198000.XESCANDA, " + //el 40º
          "T6198000.XPETDAT1, " +
          "T6198000.XPETDAT2, " +
          "T6198000.XPETDAT3, " +
          "T6198000.XINFOCAN, " +
          "T6198000.XINFORME, " +
          "T6198000.XSUPELIM, " +
          "T6198000.XAPLIUMB, " +
          "T6198000.QLIMSURT, " +
          "T6198000.CFAMILIA, " +
          "T6198000.FARTIPVF, " +
          "T6198000.IARTPVPF, " +
          "T6198000.NDIGREFE, " +
          "T6198000.FMODARTI, " +
          "T6198000.CMENSTIC, " +
          "T6198000.XSTOCKME, " +
          "T6198000.QCANTPUN, " +
          "T6198000.XSURTHOR, " +
          "T6198000.QCANTENV, " +
          "T6198000.QUNIDENV, " +
          "T6198000.DARTLIN4, " +
          "T6198000.CARTCORT, " +
          "T6198000.XENLAZAD, " +
          "T6198000.CARTENLA, " +
          "T6198000.XCAMPREC, " +
          "T6198000.XESSENTI, " + 
          "T6198000.CMORATOR" */ //el 64º
          "INTO T6198000 " +
          "values ( ? , ? , ? , '', " + //CEMPRESA, CARTREFE, DARTREFE, DARTCORT
          "'', '', '', ?, " + //DARTLIN1, DARTLIN2, DARTLIN3, IARTPVPA
          "'001', null, '00', null, " + //CDEPARTM, CGRUPENV, CVTAREST, CTIPIMPU
          "'01', null, '0', '0000', " + //CUNMEASU, COFERTAS, CTIPOFER, HINICUAR
          "'0000', 0, '0', '0', " + //HFINCUAR, IARTPCPF, QMAXUDTR, QUDSUMBR
          "'0', '0', '0', 0, " + //XAPLUMBR, QUDREGTE, QUDREGDA, IPVPLOTE
          "'0', '0', '0', '0', " + //QLOTEXTN, QARTLOTE, QUDPARTI, QARTDIST
          "null, '0', '0', '0', " + //CPROMOCI, XPRECREQ, XTALLREQ, XCOLOREQ
          "'0', '0', '0', '1', " + //XDIBUREQ, XDEVNOPE, XDTONOPE, XVTANOPE
          "'0', '0', '0', '0', " + //XETIMAGN, XARTREOF, XEXCGLOB, XESCANDA
          "'0', '0', '0', '0', " + //XPETDAT1, XPETDAT2, XPETDAT3, XINFOCAN
          "'0', '0', '0', 0, " + //XINFORME, XSUPELIM, XAPLIUMB, QLIMSURT
          "null, null, 0, null, " + //CFAMILIA, FARTIPVF, IARTPVPF, NDIGREFE
          "'20010319000000', null, '0', null, " + //FMODARTI, CMENSTIC, XSTOCKME, QCANTPUN
          "'0', null, null, null, " + //XSURTHOR, QCANTENV, QUNIDENV, DARTLIN4
          "null, '0', null, '0', '0', null )"; //CARTCORT, XENLAZAD, CARTENLA, XCAMPREC, XESSENTI, CMORATOR
          
          PreparedStatement prepStmt = 
                con.prepareStatement(insertStatement);

          this.pk.cempresa = thecempresa;
          this.pk.cartrefe = thecartrefe;
          this.dartrefe = thedartrefe;
          this.iartpvpa = theiartpvpa;
          
          prepStmt.setString(1, this.pk.cempresa);
          prepStmt.setString(2, this.pk.cartrefe);
          prepStmt.setString(3, this.dartrefe);
          prepStmt.setDouble(4, this.iartpvpa);

          prepStmt.executeUpdate();
          prepStmt.close();
   }

   private void deleteRow(ItemKey pk) throws SQLException {

      String deleteStatement =
            "delete from T6198000 where cempresa = ? and cartrefe = ? ";
      PreparedStatement prepStmt =
            con.prepareStatement(deleteStatement);

      prepStmt.setString(1, pk.cempresa);
      prepStmt.setString(2, pk.cartrefe);
      prepStmt.executeUpdate();
      prepStmt.close();
   }

   private boolean selectByPrimaryKey(ItemKey primaryKey) 
      throws SQLException {

      String selectStatement =
            "elect dartrefe, iartpvpa " +
            "from T6198000 where cempresa = ? and cartrefe = ?";
      PreparedStatement prepStmt =
            con.prepareStatement(selectStatement);
      prepStmt.setString(1, primaryKey.getCompanyId());
      prepStmt.setString(2, primaryKey.getItemId());
      
      ResultSet rs = prepStmt.executeQuery();
      boolean result = rs.next();
      
      pk = primaryKey;
/*      this.cempresa = primaryKey.getCompanyId();
      this.cartrefe = primaryKey.getItemId();*/
      this.dartrefe = rs.getString(1);
      this.iartpvpa = rs.getDouble(2);

// DEBUG      System.out.println("selectByPrimaryKey: cartrefe=" + this.cartrefe);
      
      prepStmt.close();

      return result;
   }

   private Collection selectByItemIdPattern(String itemIdPattern) 
      throws SQLException {

      String selectStatement =
         "select cempresa, cartrefe " +
         "from T6198000 where cartrefe like ?";
      PreparedStatement prepStmt = 
            con.prepareStatement(selectStatement);

      prepStmt.setString(1, itemIdPattern);
      ResultSet rs = prepStmt.executeQuery();
      ArrayList a = new ArrayList();

      while (rs.next()) {
         a.add(
              new ItemKey(
                  rs.getString(1),
                  rs.getString(2)
                  )
         );
      }

      prepStmt.close();
      return a;
   }

/*   private Collection selectInRange(double low, double high) 
      throws SQLException {

      String selectStatement =
            "select id from account " +
            "where balance between  ? and ?";
      PreparedStatement prepStmt = 
            con.prepareStatement(selectStatement);

      prepStmt.setDouble(1, low);
      prepStmt.setDouble(2, high);
      ResultSet rs = prepStmt.executeQuery();
      ArrayList a = new ArrayList();

      while (rs.next()) {
         String id = rs.getString(1);
         a.add(id);
      }

      prepStmt.close();
      return a;
   }
*/
   private void loadRow() throws SQLException {

      String selectStatement =
            "select dartrefe, iartpvpa " +
            "from T6198000 where cempresa = ? and cartrefe = ?";
      PreparedStatement prepStmt = 
            con.prepareStatement(selectStatement);

      prepStmt.setString(1, this.pk.cempresa);
      prepStmt.setString(2, this.pk.cartrefe);

      ResultSet rs = prepStmt.executeQuery();

      if (rs.next()) {
// DEBUG         System.out.println("loadRow OK: dartrefe=" + this.dartrefe);
          
         this.dartrefe = rs.getString(1);
         this.iartpvpa = rs.getDouble(2);
         prepStmt.close();
      }
      else {
// DEBUG         System.out.println("loadRow KA");
         
         prepStmt.close();
         throw new NoSuchEntityException("Row for id " + pk +
            " not found in database.");
      }
   }


   private void storeRow() throws SQLException {

      String updateStatement =
            "update T6198000 set dartrefe =  ? ," +
            "iartpvpa = ? " +
            "where cempresa = ? and cartrefe = ?";
      PreparedStatement prepStmt = 
            con.prepareStatement(updateStatement);

      prepStmt.setString(1, this.dartrefe);
      prepStmt.setDouble(2, this.iartpvpa);
      prepStmt.setString(3, this.pk.cempresa);
      prepStmt.setString(4, this.pk.cartrefe);
      int rowCount = prepStmt.executeUpdate();
      prepStmt.close();

      if (rowCount == 0) {
         throw new EJBException("Storing row for id " + pk + " failed.");
      }
   }

} // ItemEJB 