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.link.HostLinkSample;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.links2.Link2SamplesService;
import ru.yandex.webmaster3.storage.links2.dao.ExternalLinks2SamplesCHDao;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Operator;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.TextCondition;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.links.LinkSamplesResponse;

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

    @Override
    public LinkSamplesResponse process(GetExternalLinkSamplesRequest request) {
        Condition linkCondition = LinkConditionConverter.convertLinkCondition(request.getParameterFilters(), request.isDeleted());
        if (request.getSourceHostId() != null) {
            linkCondition = linkCondition.andThen(new TextCondition(
                    ExternalLinks2SamplesCHDao.F.SOURCE_HOST_ID.getName(), Operator.EQUAL, request.getSourceHostId().toStringId()));
        }

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

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

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