package trail.lifecycle;

import javax.ejb.*;
import javax.annotation.*;
import java.util.*;
import java.io.Serializable;

@Stateful
public class SessionCalculator implements Calculator, Serializable {

  public ArrayList <Integer> starts, ends;
  public ArrayList <Double> growthrates, savings, results;

  @PostConstruct
  public void initialize () {
    System.err.println("Init is called");
    starts = new ArrayList <Integer> ();
    ends = new ArrayList <Integer> ();
    growthrates = new ArrayList <Double> ();
    savings = new ArrayList <Double> ();
    results = new ArrayList <Double> ();

    SessionRecord.totalSess++;
    SessionRecord.activeSess++;
  }

  @PreDestroy
  public void exit () {
    System.err.println("exit is called");
    SessionRecord.activeSess--;
  }

  @PrePassivate
  public void serialize () {
    System.err.println("serialize is called");
    SessionRecord.pausedSess++;
  }

  @PostActivate
  public void activate () {
    System.err.println("activate is called");
    SessionRecord.pausedSess--;
  }

  @Remove
  public void stopSession () {
    // Call to this method signals the container
    // to remove this bean instance and terminates
    // the session.
  }

  public double calculate (int start, int end, double growthrate, double saving) {
    double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1);
    double result = saving * 12. * (tmp - 1) / growthrate;

    starts.add(Integer.valueOf(start));
    ends.add(Integer.valueOf(end));
    growthrates.add(Double.valueOf(growthrate));
    savings.add(Double.valueOf(saving));
    results.add(Double.valueOf(result));

    return result;
  }

  public ArrayList <Integer> getStarts () {
    return starts;
  }

  public ArrayList <Integer> getEnds () {
    return ends;
  }

  public ArrayList <Double> getGrowthrates () {
    return growthrates;
  }

  public ArrayList <Double> getSavings () {
    return savings;
  }

  public ArrayList <Double> getResults () {
    return results;
  }

}
