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

import java.util.Objects;

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

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 10/12/2020.
 * Маркетные фиды
 */
@Repository
public class TurboMarketFeedsYDao extends AbstractYDao {

    public TurboMarketFeedsYDao() {
        super(PREFIX_TURBO, "turbo_market_feeds");
    }

    public boolean hasActiveFeeds(String domain) {
        return Objects.requireNonNull(queryOne(select().countAll().where(F.DOMAIN.eq(domain)).and(F.IS_FEED_ENABLED.eq(true)).getStatement(),
                DataMapper.SINGLE_COLUMN_INT_MAPPER)) > 0;
    }

    public void clearOldRecords(DateTime dateTime) {
        execute(delete().where(F.UPDATE_DATE.lt(dateTime)).getStatement());
    }

    private interface F {
        Field<String> DOMAIN = Fields.stringField("domain");
        Field<String> FEED_URL = Fields.stringField("feed_url");
        Field<String> FEED_ID = Fields.stringField("feed_id");
        Field<Boolean> IS_FEED_ENABLED = Fields.boolField("is_feed_enabled");
        Field<String> DATASOURCE_ID = Fields.stringField("datasource_id");
        Field<String> DATASOURCE_NAME = Fields.stringField("datasource_name");
        Field<String> CAMPAIGN_ID = Fields.stringField("campaign_id");
        Field<DateTime> UPDATE_DATE = Fields.jodaDateTimeField("update_date");
    }

}
