package trail.entity.basic;

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

@Stateless
public class EntityCalculator implements Calculator {

  @PersistenceContext // (unitName="cal")
  protected EntityManager em;

  public void addFund (String name, double growthrate) {
    Fund fund = new Fund (name, growthrate);
    em.persist (fund);
  }

  public void addInvestor (String name, int start, int end) {
    Investor investor = new Investor (name, start, end);
    em.persist (investor);
  }

  public double calculate (int fundId, int investorId, double saving) {

    Investor investor =
        em.find(Investor.class,
                Integer.valueOf(investorId));
    Fund fund =
        em.find(Fund.class,
                Integer.valueOf(fundId));

    int start = investor.getStartAge();
    int end = investor.getEndAge();
    double growthrate = fund.getGrowthrate();

    double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1);
    double result = saving * 12. * (tmp - 1) / growthrate;
    Timestamp ts = new Timestamp (System.currentTimeMillis());

    TimedRecord rec =
        new TimedRecord (fund, investor, saving, result, ts);
    em.persist (rec);

    return result;
  }

  public Collection<Fund> getFunds () {
    return em.createQuery("from Fund f").getResultList();
  }
  public Collection <Investor> getInvestors () {
    return em.createQuery("from Investor p").getResultList();
  }
  public Collection <TimedRecord> getRecords () {
    return em.createQuery("from TimedRecord r order by r.ts desc").getResultList();
  }

}
