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

import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.storage.util.ydb.AbstractYDao;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.DataMapper;
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 11/09/2018.
 */
@Repository
public class TurboFeedsSamplesYDao extends AbstractYDao {

    public TurboFeedsSamplesYDao() {
        super(PREFIX_TURBO, "turbo_feeds_samples");
    }

    public void putContent(String domain, TurboFeedType type, String content) {
        upsert(F.DOMAIN.value(domain), F.TYPE.value(type), F.CONTENT.value(content), F.UPDATE_DATE.value(DateTime.now())).execute();
    }

    public void refreshUpdateDate(String domain, TurboFeedType type) {
        update().with(F.UPDATE_DATE.set(DateTime.now())).where(F.DOMAIN.eq(domain)).and(F.TYPE.eq(type)).execute();
    }

    public Pair<String, DateTime> getContentAndUpdateDate(String domain, TurboFeedType type) {
        return select(PAIR_MAPPER).where(F.DOMAIN.eq(domain)).and(F.TYPE.eq(type)).queryOne();
    }

    private static final DataMapper<Pair<String, DateTime>> PAIR_MAPPER = DataMapper.create(
            F.CONTENT, F.UPDATE_DATE, Pair::of
    );

    private interface F {
        Field<String> DOMAIN = Fields.stringField("domain");
        Field<TurboFeedType> TYPE = Fields.intEnumField("type", TurboFeedType.R);
        Field<String> CONTENT = Fields.stringField("content").makeOptional();
        Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");
    }
}
