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

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

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.searchurls.data.ApiSearchUrlSample;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.searchurl.SearchUrlSamplesService;
import ru.yandex.webmaster3.storage.searchurl.samples.data.SearchUrlSample;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;

/**
 * @author avhaliullin
 */
@Description("Примеры страниц сайта в поиске")
@Category("searchurls")
@Component
public class SearchUrlSamplesAction extends AbstractApiAction<SearchUrlSamplesRequest, SearchUrlSamplesResponse> {
    private SearchUrlSamplesService searchUrlSamplesService;

    public SearchUrlSamplesAction() {
        super(Permission.COMMON);
    }

    @Override
    public SearchUrlSamplesResponse process(SearchUrlSamplesRequest request) {
        WebmasterHostId hostId = request.getHostId();
        int limit = request.getLimit();
        int offset = request.getOffset();

        Condition trueCondition = Condition.trueCondition();
        int count = (int) searchUrlSamplesService.getSearchUrlSamplesCount(hostId, trueCondition, trueCondition);
        if (count == 0 || offset >= count) {
            return new SearchUrlSamplesResponse(count, Collections.emptyList());
        }

        // получим сэмплы
        List<SearchUrlSample> rawSamples = searchUrlSamplesService.getSearchUrlSamples(
                hostId, trueCondition, trueCondition, offset, limit);

        // и приведем их к нужному виду
        List<ApiSearchUrlSample> samples = rawSamples.stream()
                .map(ApiSearchUrlSample::fromSearchUrlSample)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new SearchUrlSamplesResponse(count, samples);
    }

    @Required
    public void setSearchUrlSamplesService(SearchUrlSamplesService searchUrlSamplesService) {
        this.searchUrlSamplesService = searchUrlSamplesService;
    }
}
