package trail.security;

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

import org.jboss.annotation.security.SecurityDomain;

@Stateless
@SecurityDomain("other")
public class SecureCalculator implements Calculator {

  @PersistenceContext
  protected EntityManager em;

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

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

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

  @RolesAllowed({"RegularUser"})
  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;
  }
}
