package de.ivu.elect.presentation.charts;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

import javax.inject.Inject;

import org.primefaces.model.charts.ChartData;
import org.primefaces.model.charts.optionconfig.legend.Legend;
import org.primefaces.model.charts.pie.PieChartDataSet;
import org.primefaces.model.charts.pie.PieChartModel;
import org.primefaces.model.charts.pie.PieChartOptions;

import de.ivu.elect.jee.faces.UserLocale;

public class PieChartJsModelBuilder implements Serializable {

  private static final long serialVersionUID = 1L;

  @Inject
  private transient UserLocale userLocale;

  public <K> PieChartModel createPieChartModel(List<K> keyList, Function<K, Long> valueFct, Function<K, String> colorFct, Function<K, String> labelFct) {

    PieChartModel result = new PieChartModel();
    ChartData data = new ChartData();
    PieChartDataSet dataSet = new PieChartDataSet();
    List<Number> values = new ArrayList<>();
    List<String> bgColors = new ArrayList<>();
    List<String> labels = new ArrayList<>();

    for (K key : keyList) {
      Long number = valueFct.apply(key);
      values.add(number);
      bgColors.add("#" + colorFct.apply(key));
      labels.add(labelFct.apply(key) + " (" + userLocale.formatNumber(number) + ")");
    }

    dataSet.setData(values);
    dataSet.setBackgroundColor(bgColors);

    data.addChartDataSet(dataSet);
    data.setLabels(labels);
    result.setData(data);

    PieChartOptions pieChartOptions = new PieChartOptions();
    Legend legend = new Legend();
    pieChartOptions.setLegend(legend);
    legend.setPosition("bottom");
    result.setOptions(pieChartOptions);
    return result;
  }
}
