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

import org.jetbrains.annotations.Nullable;
import org.joda.time.DateTime;
import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSampleInfo;
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;

/**
 * @author leonidrom
 *
 * У таблицы ttl 90 дней по полю ttl_date
 */
@Repository
public class MetrikaCrawlSamplesInfoYDao extends AbstractYDao {
    private static final String TABLE_NAME = "metrika_crawl_samples_info";

    public MetrikaCrawlSamplesInfoYDao() {
        super(PREFIX_METRIKA, TABLE_NAME);
    }

    public void save(MetrikaCrawlSampleInfo sampleInfo) {
        upsert(
                F.DOMAIN.value(sampleInfo.getDomain()),
                F.COUNTER_ID.value(sampleInfo.getCounterId()),
                F.CRAWL_SUSPENDED.value(sampleInfo.isCrawlSuspended()),
                F.LAST_UPDATE.value(sampleInfo.getLastUpdated()),
                F.TTL_DATE.value(DateTime.now())
        ).execute();
    }

    @Nullable
    public MetrikaCrawlSampleInfo getSampleInfo(String domain, long counterId) {
        return select(MAPPER)
                .where(F.DOMAIN.eq(domain))
                .and(F.COUNTER_ID.eq(counterId))
                .queryOne();
    }

    private static DataMapper<MetrikaCrawlSampleInfo> MAPPER = DataMapper.create(
            F.DOMAIN, F.COUNTER_ID, F.CRAWL_SUSPENDED, F.LAST_UPDATE, MetrikaCrawlSampleInfo::new
    );

    private static class F {
        static final Field<String> DOMAIN = Fields.stringField("domain");
        static final Field<Long> COUNTER_ID = Fields.longField("counter_id");
        static final Field<Boolean> CRAWL_SUSPENDED = Fields.boolField("crawl_suspended");
        static final Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
        static final Field<DateTime> TTL_DATE = Fields.jodaDateTimeField("ttl_date");
    }
}
