package trail.injection;

import javax.ejb.Stateless;
import javax.ejb.TimerService;
import javax.ejb.SessionContext;
import javax.annotation.Resource;
import javax.jms.QueueConnectionFactory;
import javax.jms.Queue;
import java.sql.*;
import javax.sql.*;

@Stateless
public class RecordManagerBean implements RecordManager {

  // Inject resources based on global jndi names
  @Resource (mappedName="java:/DefaultDS")
  DataSource myDb;

  @Resource (mappedName="ConnectionFactory")
  QueueConnectionFactory factory;

  @Resource (mappedName="queue/testQueue")
  Queue queue;

  // Inject resources based on type
  @Resource
  TimerService tms;

  @Resource
  SessionContext ctx;

  public void addRecord (long sent, double result) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {

      conn = myDb.getConnection();
      pstmt = conn.prepareStatement (
              "INSERT INTO INJECTIONREC " +
              "(SENT,PROCESSED,RESULT) " +
              "VALUES (?, ?, ?)");
      pstmt.setLong (1, sent);
      long processed = System.currentTimeMillis();
      pstmt.setLong (2, processed);
      pstmt.setDouble (3, result);
      pstmt.executeUpdate();

    } catch (Exception e) {
      e.printStackTrace ();
    } finally {
      try {
        pstmt.close ();
        conn.close ();
      } catch (Exception e) {
        e.printStackTrace ();
      }
    }
  }

  public CalculationRecord getRecord (long sent) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;

    CalculationRecord rc = null;

    try {

      conn = myDb.getConnection();
      stmt = conn.createStatement ();
      rs = stmt.executeQuery("SELECT * FROM INJECTIONREC");

      while (rs.next()) {
        if (rs.getLong("sent") == sent) {
          rc = new CalculationRecord (
              rs.getLong ("sent"),
              rs.getLong ("processed"),
              rs.getDouble ("result"));
          break;
        }
      }

    } catch (Exception e) {
      e.printStackTrace ();
    } finally {
      try {
        rs.close ();
        stmt.close ();
        conn.close ();
      } catch (Exception e) {
        e.printStackTrace ();
      }
    }
    return rc;
  }

}