
package de.ivu.elect.jee.database;

import java.io.Serializable;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

import org.primefaces.model.chart.AxisType;
import org.primefaces.model.chart.CategoryAxis;
import org.primefaces.model.chart.LineChartModel;
import org.primefaces.model.chart.LineChartSeries;

@RequestScoped
public class DatabaseMaxTimeController implements Serializable {

  private static final long serialVersionUID = 1L;

  private transient LineChartModel model;

  @Inject
  private transient DatabaseStatistikStore store;

  public DatabaseMaxTimeController() {
    super();
  }

  private void createModel() {
    // model
    model = new LineChartModel();
    List<DatabaseStatistikData> daten = store.getData();
    Collections.sort(daten);

    addSeries(daten, "Max Creation Time", DatabaseTimeData::getMaxCreationTime);
    addSeries(daten, "Max Get Time", DatabaseTimeData::getMaxGetTime);
    addSeries(daten, "Max Usage Time", DatabaseTimeData::getMaxUsageTime);
    addSeries(daten, "Max Wait Time", DatabaseTimeData::getMaxWaitTime);

    model.setLegendPosition("ne");
    model.getAxes().put(AxisType.X, new CategoryAxis("Zeitpunkt"));
    model.getAxis(AxisType.X).setTickAngle(270);

    model.getAxis(AxisType.Y).setMin(0);
    model.getAxis(AxisType.Y).setLabel(" Zeit in ms ");

    model.setZoom(true);
  }

  private void addSeries(List<DatabaseStatistikData> daten, String name, Function<DatabaseTimeData, Long> getter) {
    LineChartSeries series = new LineChartSeries();
    series.setLabel(name);
    model.addSeries(series);
    DateFormat dateTimeInstance = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM, Locale.GERMANY);
    for (DatabaseStatistikData d : daten) {
      String dateTime = dateTimeInstance.format(new Date(d.getZeitpunkt()));
      series.set(dateTime, getter.apply(d.getTimeData()));
    }
  }

  public LineChartModel getModel() {
    if (model == null) {
      createModel();
    }
    return model;
  }

}
