package ru.yandex.wmconsole.viewer.api.servantlet.history;

import java.util.Date;
import java.util.List;
import java.util.NavigableMap;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.UserErrorOptions;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostDbHostInfo;
import ru.yandex.wmconsole.service.ErrorInfoService;
import ru.yandex.wmconsole.service.HostDbHostInfoService;
import ru.yandex.wmconsole.util.UrlErrorGrouper;
import ru.yandex.wmconsole.viewer.api.SiteHistoryType;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author aherman
 */
public class ApiGetExcludedUrlsCountHistoryServantlet extends AbstractApiGetHistoryServantlet {
    private ErrorInfoService errorInfoService;
    private HostDbHostInfoService hostDbHostInfoService;

    private int showDurationMonth = 6;

    @Override
    protected NavigableMap<Date, Long> getHistoryData(BriefHostInfo briefHostInfo, SiteHistoryType historyType, long userId)
            throws InternalException
    {
        UserErrorOptions userErrorOptions = errorInfoService.getUserErrorOptions(userId, briefHostInfo.getId());
        List<Integer> notOkErrorCodes = UrlErrorGrouper.expandGroups(userErrorOptions.getNotOkSeverityCodesWithGroups());
        HostDbHostInfo hostDbHostInfo = hostDbHostInfoService.getHostDbHostInfo(briefHostInfo.getName());

        DateTime fromDate = DateTime.now().minusMonths(showDurationMonth);

        return indexHistoryService.getErrorsHistoryForTrend(hostDbHostInfo, notOkErrorCodes, fromDate.toDate());
    }

    @Override
    protected SiteHistoryType getHistoryType() {
        return SiteHistoryType.EXCLUDED_URLS_COUNT;
    }

    @Override
    public ApiOAuthPermission getRequiredPermission() {
        return ApiOAuthPermission.COMMON_OPERATIONS;
    }

    @Required
    public void setErrorInfoService(ErrorInfoService errorInfoService) {
        this.errorInfoService = errorInfoService;
    }

    @Required
    public void setHostDbHostInfoService(HostDbHostInfoService hostDbHostInfoService) {
        this.hostDbHostInfoService = hostDbHostInfoService;
    }

    public void setShowDurationMonth(int showDurationMonth) {
        this.showDurationMonth = showDurationMonth;
    }
}
