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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
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.ApiLinkSample;
import ru.yandex.webmaster3.core.link.HostLinkSample;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.storage.links2.ExternalLinksOrder;
import ru.yandex.webmaster3.storage.links2.Link2SamplesService;
import ru.yandex.webmaster3.storage.util.clickhouse2.query.OrderBy;

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

/**
 * @author avhaliullin
 */
@Description("Получить примеры внешних ссылок на страницы сайта")
@Category("links")
@Component("externalLinkSamplesAction")
public class ExternalLinkSamplesAction extends AbstractApiAction<ExternalLinkSamplesRequest, ExternalLinkSamplesResponse> {
    private final Link2SamplesService link2SamplesService;

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

    @Override
    public ExternalLinkSamplesResponse process(ExternalLinkSamplesRequest request) {
        long count = link2SamplesService.countExternalSamples(request.getHostId(), false, false, null);
        List<HostLinkSample> samples = link2SamplesService.listExternalSamples(
                request.getHostId(),
                request.getOffset(),
                request.getLimit(),
                null,
                false,
                ExternalLinksOrder.LINK_DATE,
                OrderBy.Direction.DESC,
                false
        );

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

        return new ExternalLinkSamplesResponse(count, result);
    }
}
