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

import java.util.Collections;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;

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

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.link.LinkHistoryIndicatorType;
import ru.yandex.webmaster3.storage.links.LinksService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.links.HistoryUtil;

/**
 * @author tsyplyaev
 */
@ReadAction
@Description("Ручка для графиков истории по количеству внутренних и внешних ссылок")
@Category("links")
public class GetExternalLinksHistoryAction extends AbstractUserVerifiedHostAction<GetExternalLinksHistoryRequest, GetExternalLinksHistoryResponse> {
    private LinksService linksService;
    private LinkHistoryIndicatorType indicator;

    @Override
    public GetExternalLinksHistoryResponse process(GetExternalLinksHistoryRequest request) {
        Map<LinkHistoryIndicatorType, NavigableMap<LocalDate, Long>> linksHistory =
                linksService.getSimpleHistory(request.getHostId());

        Optional<NavigableMap<LocalDate, Long>> urlCountHistory = linksHistory.entrySet().stream()
                .filter(e -> e.getKey() == indicator)
                .map(Map.Entry::getValue)
                .findFirst();

        if (!urlCountHistory.isPresent()) {
            return new GetExternalLinksHistoryResponse.OrdinaryResponseLinks(Collections.emptyList());
        }

        return new GetExternalLinksHistoryResponse.OrdinaryResponseLinks(
                Collections.singletonList(
                        new GetExternalLinksHistoryResponse.LinkHistory(
                                indicator,
                                HistoryUtil.toDataPoint(urlCountHistory.get())
                        )
                )
        );
    }

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

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