package ru.yandex.webmaster3.viewer.http.links;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;

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

import ru.yandex.webmaster3.core.codes.ErrorGroupEnum;
import ru.yandex.webmaster3.core.data.HttpCodeInfo;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.storage.links.LinksService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * @author aherman
 */
@ReadAction
@Category("links")
public class GetInternalLinkBrokenHttpCodesHistoryAction extends
        AbstractUserVerifiedHostAction<GetInternalLinkBrokenHttpCodesHistoryRequest, GetInternalLinkBrokenHttpCodesHistoryResponse>
{
    private LinksService linksService;
    private LinkIndicator.Broken indicator;

    @Override
    public GetInternalLinkBrokenHttpCodesHistoryResponse process(GetInternalLinkBrokenHttpCodesHistoryRequest request) {
        Map<HttpCodeInfo, NavigableMap<LocalDate, Long>>
                httpCodeHistory = linksService.getInternalHttpHistory(request.getHostId(), request.getDateFrom(), request.getDateTo());
        List<GetInternalLinkBrokenHttpCodesHistoryResponse.HttpCodeHistory> result = new ArrayList<>();

        ErrorGroupEnum group = LinkIndicator.toGroup(indicator);
        for (Map.Entry<HttpCodeInfo, NavigableMap<LocalDate, Long>> entry : httpCodeHistory.entrySet()) {
            if (!group.contains(entry.getKey().getCode())) {
                continue;
            }
            result.add(new GetInternalLinkBrokenHttpCodesHistoryResponse.HttpCodeHistory(
                    entry.getKey(),
                    HistoryUtil.toDataPoint(entry.getValue())
            ));
        }
        return new GetInternalLinkBrokenHttpCodesHistoryResponse.NormalResponse(result);
    }

    @Required
    public void setLinksService(LinksService linksService) {
        this.linksService = linksService;
    }

    @Required
    public void setIndicator(LinkIndicator.Broken indicator) {
        this.indicator = indicator;
    }
}
