package ru.yandex.wmconsole.servantlet.graphics;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.KPIInfoService;
import ru.yandex.wmtools.common.data.plot.DateDoublePlotHelper;
import ru.yandex.wmtools.common.data.plot.HighchartPlotDataWrapper;
import ru.yandex.wmtools.common.data.plot.PlotHelper;
import ru.yandex.wmtools.common.data.plot.UnixTimestampDateFormat;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

import java.util.*;

import org.springframework.beans.factory.annotation.Required;

/**
 * @author avhaliullin
 */
public class KPIPlotDataServantlet extends WMCAuthenticationServantlet {
    private static final String PARAM_IDS = "id";
    private KPIInfoService kpiInfoService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        List<Integer> kpis = Arrays.asList(getMultiParamInt(req, PARAM_IDS));
        Map<String, NavigableMap<Date, Double>> plot = kpiInfoService.getPlotData(kpis);
        List<String> labels = new ArrayList<String>();
        List<NavigableMap<Date, Double>> plots = new ArrayList<NavigableMap<Date, Double>>();
        for (Map.Entry<String, NavigableMap<Date, Double>> entry : plot.entrySet()) {
            labels.add(entry.getKey());
            plots.add(entry.getValue());
        }
        DateDoublePlotHelper plotHelper = new DateDoublePlotHelper(PlotHelper.InterpolateMode.NULL);
        plotHelper.setDateFormat(new UnixTimestampDateFormat(true));
        res.addData(new HighchartPlotDataWrapper<Date, Double>("kpi-plot", plots, labels, plotHelper));
    }

    @Required
    public void setKpiInfoService(KPIInfoService kpiInfoService) {
        this.kpiInfoService = kpiInfoService;
    }
}
