package ru.yandex.webmaster3.storage.metrika;

import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.joda.time.Instant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ru.yandex.webmaster3.storage.metrika.dao.MetrikaCrawlSamplesCHDao;
import ru.yandex.webmaster3.storage.metrika.dao.MetrikaCrawlSamplesInfoYDao;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSample;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSampleInfo;
import ru.yandex.webmaster3.storage.util.clickhouse2.ClickhouseException;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;

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

/**
 * @author leonidrom
 */
@Service("metrikaCrawlSamplesService")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class MetrikaCrawlSamplesService {
    private final MetrikaCrawlSamplesCHDao mdbMetrikaCrawlSamplesCHDao;
    private final MetrikaCrawlSamplesInfoYDao metrikaCrawlSamplesInfoYDao;

    public boolean hasSamples(String domain, long counterId) {
        try {
            long samplesCount = getSamplesCount(domain, counterId, Condition.trueCondition());
            return samplesCount > 0;
        } catch (ClickhouseException e) {
            throw e.asUnchecked();
        }
    }

    public long getSamplesCount(String domain, long counterId, Condition condition) {
        try {
            return mdbMetrikaCrawlSamplesCHDao.getSamplesCount(domain, counterId, condition);
        } catch (ClickhouseException e) {
            throw e.asUnchecked();
        }
    }

    public List<MetrikaCrawlSample> getSamples(String domain, long counterId, Condition condition, long limitFrom,
                                               long limitSize) {
        try {
            return mdbMetrikaCrawlSamplesCHDao.getSamples(domain, counterId, condition, limitFrom, limitSize);
        } catch (ClickhouseException e) {
            throw e.asUnchecked();
        }
    }

    public List<MetrikaCrawlSample> getSamples(String domain, long counterId, Condition condition) {
        try {
            long totalSamples = getSamplesCount(domain, counterId, condition);
            if (totalSamples > 0) {
                return mdbMetrikaCrawlSamplesCHDao.getSamples(domain, counterId, condition, 0, totalSamples);
            } else {
                return Collections.emptyList();
            }
        } catch (ClickhouseException e) {
            throw e.asUnchecked();
        }
    }

    @NotNull
    public Instant getSampleLastUpdateTime(String domain, long counterId) {
        MetrikaCrawlSampleInfo sampleInfo = metrikaCrawlSamplesInfoYDao.getSampleInfo(domain, counterId);
        if (sampleInfo == null) {
            return new Instant(0);
        } else {
            return sampleInfo.getLastUpdated().toInstant();
        }
    }
}
