package ru.yandex.webmaster3.storage.turbo.service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

import com.google.common.base.Suppliers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.turbo.model.statistics.TurboClicksDayStatistics;
import ru.yandex.webmaster3.core.turbo.model.statistics.TurboClicksStatistics;
import ru.yandex.webmaster3.core.turbo.model.statistics.TurboTopUrlInfo;
import ru.yandex.webmaster3.storage.searchquery.importing.dao.YtClickhouseDataLoadYDao;
import ru.yandex.webmaster3.storage.settings.SettingsService;
import ru.yandex.webmaster3.storage.turbo.dao.statistics.MdbTurboClicksDayStatisticsCHDao;
import ru.yandex.webmaster3.storage.ytimport.YtClickhouseDataLoadType;


/**
 * ishalaru
 * 10.03.2020
 **/
@Service("turboClickStatisticsService")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class TurboClickStatisticsService {

    private final MdbTurboClicksDayStatisticsCHDao mdbTurboClicksDayStatisticsCHDao;
    private final YtClickhouseDataLoadYDao ytClickhouseDataLoadYDao;

    private final Supplier<LocalDate> LAST_UPDATE_DATE_SUPPLIER = Suppliers.memoizeWithExpiration(
            this::loadMdbLastUpdateDate, 10, TimeUnit.MINUTES
    );

    public TurboClicksStatistics turboClickStatistics(String domain) {
        return turboClicksDayStatistics(domain);
    }

    private TurboClicksStatistics turboClicksDayStatistics(String domain) {
        LocalDate date = getLastImportedDate(domain);
        List<TurboClicksDayStatistics> list = list(domain, date.minusDays(7), date);
        long totalClicks = 0;
        long turboClicks = 0;
        long autoparsedClicks = 0;
        for (TurboClicksDayStatistics item : list) {
            totalClicks += item.getTotalClicks();
            turboClicks += item.getTurboClicks();
            autoparsedClicks += item.getAutoparsedClicks();
        }
        return new TurboClicksStatistics(domain, totalClicks, turboClicks, autoparsedClicks, null);
    }

    public LocalDate getLastImportedDate(String domain) {
        return LAST_UPDATE_DATE_SUPPLIER.get();
    }

    public List<TurboClicksDayStatistics> list(String domain, LocalDate start, LocalDate end) {
        return mdbTurboClicksDayStatisticsCHDao.list(domain, start, end);
    }

    public List<TurboTopUrlInfo> topUrlsWithoutTurbo(String domain) {
        LocalDate date = getLastImportedDate(domain);
        return mdbTurboClicksDayStatisticsCHDao.topUrlsWithoutTurbo(domain, date);
    }

    private LocalDate loadMdbLastUpdateDate() {
        return ytClickhouseDataLoadYDao.load(YtClickhouseDataLoadType.TURBO_CLICK_DAY_STATS).getDateTo();
    }


}

