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

import java.util.Collections;
import java.util.List;

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.links2.HostLinkSourceSample;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.links2.Link2SamplesService;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * @author tsyplyaev
 */
@ReadAction
@Description("Возвращает список примеров внешних ссылок на хост")
@Category("links")
public class GetExternalLinkGroupBySourceSamplesAction
        extends AbstractUserVerifiedHostAction<GetExternalLinkGroupBySourceSamplesRequest, GetExternalLinkGroupBySourceSamplesResponse>
{
    private Link2SamplesService link2SamplesService;

    @Override
    public GetExternalLinkGroupBySourceSamplesResponse process(GetExternalLinkGroupBySourceSamplesRequest request) {
        Condition linkCondition = LinkConditionConverter.convertLinkCondition(request.getParameterFilters(), request.isDeleted());

        long totalSamples = link2SamplesService.countExternalSourceSamples(request.getHostId(),
                linkCondition,
                request.getFilterBroken(),
                request.isDeleted());

        PageUtils.LongPager page = PageUtils.getPage(request.getPage(), request.getPageSize(), totalSamples);
        if (page.isEmpty()) {
            return new GetExternalLinkGroupBySourceSamplesResponse.NormalResponse(Collections.emptyList(), totalSamples);
        }
        List<HostLinkSourceSample> samples = link2SamplesService.listExternalSourceSamples(request.getHostId(),
                page.toRangeStart(), page.getPageSize(),
                linkCondition,
                request.getFilterBroken(),
                request.getOrderBy(), request.getOrderDirection(), request.isDeleted());

        return new GetExternalLinkGroupBySourceSamplesResponse.NormalResponse(samples, totalSamples);
    }

    @Required
    public void setLink2SamplesService(Link2SamplesService link2SamplesService) {
        this.link2SamplesService = link2SamplesService;
    }
}
