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

import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.storage.turbo.service.TurboFeedRawStatsData;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Field;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.Fields;

/**
 * Created by Oleg Bazdyrev on 29/01/2020.
 */
@Repository
public class TurboPreviewCacheYDao extends AbstractYDao {

    private static final Duration TTL = Duration.standardMinutes(10L);

    protected TurboPreviewCacheYDao() {
        super(PREFIX_TURBO, "turbo_preview_cache");
    }

    public void insert(String domain, int hash, TurboFeedRawStatsData data) {
        upsert(F.DOMAIN.value(domain), F.UPDATED.value(DateTime.now()), F.HASH.value(hash), F.DATA.value(data)).execute();
    }

    public TurboFeedRawStatsData get(String domain, int hash) {
        return select(F.DATA).where(F.DOMAIN.eq(domain)).and(F.HASH.eq(hash)).and(F.UPDATED.gte(DateTime.now().minus(TTL))).queryOne();
    }

    private interface F {
        Field<String> DOMAIN = Fields.stringField("domain");
        Field<Integer> HASH = Fields.intField("hash");
        Field<DateTime> UPDATED = Fields.jodaDateTimeField("updated");
        Field<TurboFeedRawStatsData> DATA = Fields.jsonField2("data", TurboFeedRawStatsData.class);
    }
}
