package ru.yandex.webmaster3.storage.searchquery;

import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import com.google.common.base.Suppliers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.searchquery.dao.StatisticDatesYDao;

/**
 * @author aherman
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SearchqueryDatesService {

    private final StatisticDatesYDao statisticDatesYDao;

    private Supplier<Pair<LocalDate, LocalDate>> cachedDates = Suppliers.memoizeWithExpiration(this::getDates, 60, TimeUnit.SECONDS);

    public Pair<LocalDate, LocalDate> getDatesCached(WebmasterHostId hostId) {
        return cachedDates.get();
    }

    public Pair<LocalDate, LocalDate> getDates() {
        Map<StatisticDate.Type, LocalDate> dates = statisticDatesYDao.getDates().stream()
                .collect(Collectors.toMap(StatisticDate::getType, StatisticDate::getDate));
        return Pair.of(dates.get(StatisticDate.Type.MINIMUM_DATE), dates.get(StatisticDate.Type.MAXIMUM_DATE));
    }
}
