package ru.yandex.wmconsole.servantlet.errors;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;

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

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.xml.wrapper.BooleanWrapper;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostDailyStateInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.HostDailyStateService;
import ru.yandex.wmtools.common.data.plot.DateIntegerPlotHelper;
import ru.yandex.wmtools.common.data.plot.DatePlotHelper;
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 ru.yandex.wmtools.common.util.SqlUtil;

public class ErrorSummaryPlotDataServantlet extends WMCAuthorizedHostOperationServantlet {
    public static final String ERROR_SUMMARY_PLOT_NAME = "error_summary";
    public static final String SITE_ERRORS_LABEL = "site_errors";

    private static final DatePlotHelper<Integer> integerPlotHelper = new DateIntegerPlotHelper(PlotHelper.InterpolateMode.NULL);

    static {
        integerPlotHelper.setDateFormat(new UnixTimestampDateFormat(true));
    }

    private HostDailyStateService hostDailyStateService;


    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {

        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);
        // Проверяем, что сайт проиндексирован обычным роботом или быстророботом
        checkIndexed(hostInfo);

        List<HostDailyStateInfo> hostDailyStates = hostDailyStateService.getHostDailyState(userId, hostInfo);

        List<NavigableMap<Date, Integer>> data = new ArrayList<NavigableMap<Date, Integer>>();
        List<String> labels = Collections.singletonList(SITE_ERRORS_LABEL);
        final boolean needShowPlot;
        if (hostDailyStates.size() > 1) {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.MONTH, -1);
            Date monthAgo = c.getTime();
            int siteErrorsInLastMonth = 0;
            NavigableMap<Date, Integer> siteErrors = new TreeMap<Date, Integer>();
            for (HostDailyStateInfo hostDailyState : hostDailyStates) {
                if (hostDailyState.getStateDate().after(monthAgo) && hostDailyState.getSiteErrors() > 0) {
                    siteErrorsInLastMonth += hostDailyState.getSiteErrors();
                }
                siteErrors.put(hostDailyState.getStateDate(), hostDailyState.getSiteErrors());
            }
            Date currentDate = SqlUtil.getMidnightTimestamp(null);
            siteErrors.put(currentDate, siteErrors.lastEntry().getValue());
            data.add(siteErrors);
            res.addData(new HighchartPlotDataWrapper<Date, Integer>(ERROR_SUMMARY_PLOT_NAME, data, labels, integerPlotHelper));
            needShowPlot = siteErrorsInLastMonth > 0;
        } else {
            final HighchartPlotDataWrapper<Date, Integer> wrapper =
                    new HighchartPlotDataWrapper<Date, Integer>(ERROR_SUMMARY_PLOT_NAME, data, labels, integerPlotHelper, true);
            res.addData(wrapper);
            needShowPlot = false;
        }
        res.addData(new BooleanWrapper("show-plot", needShowPlot));
    }

    @Required
    public void setHostDailyStateService(HostDailyStateService hostDailyStateService) {
        this.hostDailyStateService = hostDailyStateService;
    }
}
