package ru.yandex.webmaster3.viewer.http.metrika.crawl2;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.Action;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.metrika.counters.MetrikaCountersUtil;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.metrika.MetrikaCrawlSamplesService;
import ru.yandex.webmaster3.storage.metrika.dao.MetrikaCrawlSampleCondition;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSample;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSampleInfo;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;

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

/**
 * @author leonidrom
 */
@Category("metrika")
@ReadAction
@Description("Получение семплов урлов, которые обходятся на домене по счетчику")
public class MetrikaCrawlSamplesAction extends Action<MetrikaCrawlSamplesRequest, MetrikaCrawlSamplesResponse> {
    private final MetrikaCrawlSamplesService metrikaCrawlSamplesService;

    @Autowired
    public MetrikaCrawlSamplesAction(MetrikaCrawlSamplesService metrikaCrawlSamplesService) {
        this.metrikaCrawlSamplesService = metrikaCrawlSamplesService;
    }

    @Override
    public MetrikaCrawlSamplesResponse process(MetrikaCrawlSamplesRequest request) throws WebmasterException {
        String domain = MetrikaCountersUtil.hostToPunycodeDomain(request.getHostId());
        long counterId = request.getCounterId();

        Condition condition = MetrikaCrawlSampleCondition.makeCondition(request.getParameterFilters());
        DateTime lastUpdateTime = new DateTime(metrikaCrawlSamplesService.getSampleLastUpdateTime(domain, counterId));
        long samplesCount = metrikaCrawlSamplesService.getSamplesCount(domain, counterId, condition);
        if (lastUpdateTime.getMillis() == 0 || samplesCount == 0L) {
            return new MetrikaCrawlSamplesResponse(0, Collections.emptyList(), lastUpdateTime);
        }

        long limitFrom = request.getP() * request.getPSize();
        long limitSize = request.getPSize();
        List<MetrikaCrawlSample> samples = metrikaCrawlSamplesService.getSamples(
                domain, counterId, condition, limitFrom, limitSize);

        return new MetrikaCrawlSamplesResponse(samplesCount, samples, lastUpdateTime);
    }
}
