package ru.micord.ervu_dashboard.component.chart;

import java.math.BigDecimal;
import java.util.List;

import component.chart.dto.SingleChartDataDto;
import component.chart.dto.SingleChartDataSetDto;
import model.Filter;

/**
 * @author Artyom Khakimullin
 */
public class SingleChartDataSubtractService extends RoundSingleChartDataSetService {

  @Override
  public SingleChartDataDto loadData(Integer offset, Integer limit, Filter[] filters) {
    SingleChartDataDto chartDataDto = super.loadData(offset, limit, filters);
    List<SingleChartDataSetDto> setDtoList = chartDataDto.datasets;
    for (SingleChartDataSetDto singleChartData : setDtoList) {
      List<Object> dataSets = singleChartData.getData();
      if (!dataSets.isEmpty()) {
        BigDecimal lastElement = new BigDecimal(dataSets.get(dataSets.size() - 1).toString());
        BigDecimal sum = sumWithLimit(dataSets, dataSets.size() - 1);
        BigDecimal result = lastElement.subtract(sum);
        dataSets.set(dataSets.size() - 1, result);
      }
      singleChartData.data = dataSets;
    }
    chartDataDto.setDatasets(setDtoList);
    return chartDataDto;
  }

  private BigDecimal sumWithLimit(List<Object> dataSet, int limit) {
    return dataSet.stream()
        .limit(limit)
        .map(val -> new BigDecimal(val.toString()))
        .reduce(BigDecimal.ZERO, BigDecimal::add);
  }
}
