package trail.apptrans;

import trail.entity.beans.*;
import javax.ejb.*;
import javax.persistence.*;
import java.util.*;
import java.sql.Timestamp;
import java.io.Serializable;

@Stateful
public class ApptransCalculator implements Calculator, Serializable {

  @PersistenceContext(
      // unitName="cal",
      type=PersistenceContextType.EXTENDED
  )
  protected EntityManager em;

  Collection <TimedRecord> rc;

  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  // @PostConstruct
  protected void retrieveRecords () {
    rc = em.createQuery("from TimedRecord r order by r.id desc")
            .getResultList();
  }

  public Collection <TimedRecord> getRecords () {
    retrieveRecords ();
    return rc;
  }

  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  public void updateExchangeRate (double newrate) {
    if (rc == null) {
      System.out.println ("This might indicate a problem");
      retrieveRecords ();
    }

    for (Iterator iter = rc.iterator(); iter.hasNext();) {
      TimedRecord r = (TimedRecord) iter.next();
      r.setSaving(r.getSaving() * newrate);
      r.setResult(r.getResult() * newrate);
    }
  }

  @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
  // @FlushMode(FlushModeType.NEVER)
  public void updateTimestamp () {
    if (rc == null) {
      System.out.println ("This might indicate a problem");
      retrieveRecords ();
    }
    
    for (Iterator iter = rc.iterator(); iter.hasNext();) {
      TimedRecord r = (TimedRecord) iter.next();
      r.setTs(new Timestamp (System.currentTimeMillis()));
    }
  }

  @Remove
  public void checkout() {
    // flushes all changes
    em.flush();
  }
}
