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

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.rest.AbstractApiAction;
import ru.yandex.webmaster3.api.links.data.ApiInternalLinksBrokenIndicator;
import ru.yandex.webmaster3.api.links.data.ApiLinkSample;
import ru.yandex.webmaster3.core.codes.ErrorGroupEnum;
import ru.yandex.webmaster3.core.link.HostLinkSample;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.links.InternalLinksOrder;
import ru.yandex.webmaster3.storage.links2.Link2SamplesService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author leonidrom
 */

/*
 * Путь: /user/{user-id}/hosts/{host-id}/links/internal/broken/samples/
 */
@Description("Получить примеры неработающих внутренних ссылок для сайта")
@Category("links")
@Component
public class InternalLinksBrokenSamplesAction extends AbstractApiAction<InternalLinksBrokenSamplesRequest, InternalLinksBrokenSamplesResponse> {
    private final Link2SamplesService link2SamplesService;

    @Autowired
    public InternalLinksBrokenSamplesAction(Link2SamplesService link2SamplesService) {
        super(Permission.EXTERNAL_LINKS);
        this.link2SamplesService = link2SamplesService;
    }

    @Override
    public InternalLinksBrokenSamplesResponse process(InternalLinksBrokenSamplesRequest request) {
        Set<Integer> httpCodes = getHttpCodesFromIndicators(request.getIndicators());
        long count = link2SamplesService.countInternalSamples(request.getHostId(), httpCodes);

        List<HostLinkSample> samples = link2SamplesService.listInternalSamples(
                request.getHostId(),
                httpCodes,
                InternalLinksOrder.LINK_DATE,
                request.getOffset(),
                request.getLimit()
        );

        List<ApiLinkSample> result = samples.stream()
                .map(ApiLinkSample::fromHostLinkSample)
                .collect(Collectors.toList());

        return new InternalLinksBrokenSamplesResponse(count, result);
    }

    private Set<Integer> getHttpCodesFromIndicators(Set<ApiInternalLinksBrokenIndicator> indicators) {
        Set<ErrorGroupEnum> errorGroups = indicators.stream()
                .map(ApiInternalLinksBrokenIndicator::getErrorGroup)
                .collect(Collectors.toSet());

        return errorGroups.stream()
                .flatMap(errorGroup -> errorGroup.getHttpCodes().stream())
                .collect(Collectors.toSet());
    }
}
