package trail.injection;

import javax.ejb.*;
import javax.jms.*;
import javax.annotation.*;
import java.util.StringTokenizer;
import trail.slsb.*;

@MessageDriven(activationConfig =
{
  @ActivationConfigProperty(propertyName="destinationType",
    propertyValue="javax.jms.Queue"),
  @ActivationConfigProperty(propertyName="destination",
    propertyValue="queue/injection")
})
public class CalculatorMDB implements MessageListener {

  // Inject EJBs
  @EJB (beanName="StatelessCalculator")
  Calculator cal;

  // @EJB (beanName="RecordManagerBean")
  @EJB
  RecordManager rm;

  public void onMessage (Message msg) {
    try {
      TextMessage tmsg = (TextMessage) msg;
      long sent = tmsg.getLongProperty("sent");
      StringTokenizer st =
          new StringTokenizer(tmsg.getText(), ",");

      int start = Integer.parseInt(st.nextToken());
      int end = Integer.parseInt(st.nextToken());
      double growthrate = Double.parseDouble(st.nextToken());
      double saving = Double.parseDouble(st.nextToken());

      // Calculate it with the injected stateless session bean
      double result =
          cal.calculate (start, end, growthrate, saving);

      /*

      // Calculate it again with the MDB at queue/mdb
      QueueConnection cnn = factory.createQueueConnection();
      QueueSession sess = cnn.createQueueSession(false,
                         QueueSession.AUTO_ACKNOWLEDGE);
      QueueSender sender = sess.createSender(queue);
      sender.send(msg);
      // sess.commit ();
      sess.close ();
      // Wait for the MDB to respond
      Thread.sleep (2000);

      // Compare the two results!
      boolean verify = (result ==
          trail.mdb.RecordManager.getRecord(sent.getTime()).result);

      // Get timers that are associated with this EJB
      int timers = tms.getTimers().size();

      */

      rm.addRecord (sent, result);

      System.out.println ("The onMessage() is called");

    } catch (Exception e) {
      e.printStackTrace ();
    }
  }

}
