package ru.yandex.webmaster3.api.links.action;

import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.common.data.ApiHistoryPoint;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.links.data.ApiExternalLinksIndicator;
import ru.yandex.webmaster3.core.link.LinkHistoryIndicatorType;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.storage.links.LinksService;

import java.util.*;

/**
 * @author avhaliullin
 */
@Description("Получить историю количества внешних ссылок на сайт")
@Category("links")
@Component
public class ExternalLinksHistoryAction extends AbstractApiAction<ExternalLinksHistoryRequest, ExternalLinksHistoryResponse> {
    private final LinksService linksService;

    @Autowired
    public ExternalLinksHistoryAction(LinksService linksService) {
        super(Permission.EXTERNAL_LINKS);
        this.linksService = linksService;
    }

    @Override
    public ExternalLinksHistoryResponse process(ExternalLinksHistoryRequest request) {
        Map<LinkHistoryIndicatorType, NavigableMap<LocalDate, Long>> history =
                linksService.getSimpleHistory(request.getHostId());
        Map<ApiExternalLinksIndicator, List<ApiHistoryPoint<Long>>> result =
                new EnumMap<>(ApiExternalLinksIndicator.class);

        for (ApiExternalLinksIndicator indicator : request.getIndicators()) {
            List<ApiHistoryPoint<Long>> points = new ArrayList<>();
            result.put(indicator, points);
            if (history.containsKey(indicator.getIndicator())) {
                for (Map.Entry<LocalDate, Long> entry : history.get(indicator.getIndicator()).entrySet()) {
                    points.add(new ApiHistoryPoint<>(
                            entry.getKey().toDateTimeAtStartOfDay(TimeUtils.EUROPE_MOSCOW_ZONE),
                            entry.getValue()
                    ));
                }
            }
        }
        return new ExternalLinksHistoryResponse(result);
    }
}
