package de.ivu.elect.presentation.charts;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.gson.Gson;

/**
 *  on 29.04.2015.
 */
public class BarChartDataset implements Serializable {

  private final BarChart barChart;

  private final String label;

  private final Double alpha;

  private final String color;

  private final Map<BarChartEntry, BarChartData> data = new HashMap<>();

  private transient Gson gson;

  BarChartDataset(BarChart barChart, String label, String color, double alpha) {
    this.barChart = barChart;
    this.label = label;
    this.color = color;
    this.alpha = alpha;
  }

  public BarChartDataset addData(BarChartEntry entry, Number value) {
    data.put(entry, new BarChartData(value));
    return this;
  }

  public BarChartDataset(BarChart barChart, String label) {
    this(barChart, label, null, 1.0d);
  }

  public BarChartDataset(BarChart barChart, String label, String color) {
    this(barChart, label, color, 1.0d);
  }

  public String getLabel() {
    return toJson(label);
  }

  public String getLabelRaw() {
    return label;
  }

  protected String toJson(Object o) {
    return getGson().toJson(o);
  }

  private Gson getGson() {
    if (gson == null) {
      gson = new Gson();
    }
    return gson;
  }

  public String getColors() {
    if (color == null) {
      List<String> colors = new ArrayList<>(barChart.getEntries().size());
      for (BarChartEntry entry : barChart.getEntries()) {
        colors.add(convertToRGBA(entry.getColor(), alpha));
      }
      return toJson(colors);
    }
    return toJson(convertToRGBA(color, alpha));
  }

  public static String convertToRGBA(String color, double alpha) {
    if (StringUtils.isBlank(color)) {
      return "";
    }
    String hexString = color;
    if (!hexString.startsWith("#")) {
      hexString = "#" + hexString;
    }

    int hex = Integer.decode(hexString);
    int r = (hex & 0xFF0000) >> 16;
    int g = (hex & 0xFF00) >> 8;
    int b = (hex & 0xFF);

    return "rgba(" + r + "," + g + "," + b + "," + alpha + ")";
  }

  public Map<BarChartEntry, BarChartData> getData() {
    return data;
  }

  public String getValues() {
    List<Number> values = new ArrayList<>();
    for (BarChartEntry entry : barChart.getEntries()) {
      if (data.containsKey(entry)) {
        values.add(data.get(entry).getNumber());
      } else {
        values.add(0L);
      }
    }
    return toJson(values);
  }

}
