package ru.yandex.webmaster3.viewer.http.searchurl.urls;

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

import lombok.Setter;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.UserContext;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlSamplesService;
import ru.yandex.webmaster3.storage.searchurl.samples.dao.SearchUrlConditions;
import ru.yandex.webmaster3.storage.searchurl.samples.data.SearchUrlSample;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.viewer.http.AbstractUrlFilteringAction;

/**
 * @author avhaliullin
 */
@ReadAction
@Description("Получить список примеров страниц сайта на поиске")
@Category("searchurl")
public class SearchUrlSamplesAction extends AbstractUrlFilteringAction<SearchUrlSamplesRequest, SearchUrlSamplesResponse> {
    @Setter
    private SearchUrlSamplesService searchUrlSamplesService;
    @Setter
    private SearchUrlConditions searchUrlConditions;

    @Override
    public SearchUrlSamplesResponse process(SearchUrlSamplesRequest request) throws WebmasterException {
        Condition condition = searchUrlConditions.makeCondition(request.getHostId(), false, request.getParameterFilters());
        Condition freshCondition = searchUrlConditions.makeCondition(request.getHostId(), true, request.getParameterFilters());
        UserContext.setUserId(request.getUserId());
        condition = condition.andThen(getNodeCondition(request.getNodeId(), request.getHostId(), SearchUrlConditions::buildPathCondition));
        long samplesCount = searchUrlSamplesService.getSearchUrlSamplesCount(
                request.getHostId(),
                condition, freshCondition
        );
        if (samplesCount == 0) {
            return new SearchUrlSamplesResponse(samplesCount, Collections.emptyList());
        }
        List<SearchUrlSample> samples = searchUrlSamplesService.getSearchUrlSamples(request.getHostId(), condition, freshCondition,
                request.getP() * request.getPSize(), request.getPSize());
        return new SearchUrlSamplesResponse(samplesCount, samples);
    }

}
