package ru.yandex.webmaster3.storage.searchurl;

import java.util.Objects;

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

import ru.yandex.webmaster3.core.data.WebmasterHostId;
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 05/03/2021.
 */
@Repository
public class MemorandumStatsYDao extends AbstractYDao {

    public MemorandumStatsYDao() {
        super(PREFIX_SEARCHURL, "memorandum_host_stats");
    }

    public void clearOldRecords(DateTime ts) {
        delete().where(F.LAST_UPDATE.lt(ts)).execute();
    }

    public long getBannedUrlsCount(WebmasterHostId hostId) {
        return Objects.requireNonNullElse(select(F.BANNED_URLS).where(F.HOST_ID.eq(hostId)).queryOne(), 0L);
    }

    private interface F {
        Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        Field<DateTime> LAST_UPDATE = Fields.jodaDateTimeField("last_update");
        Field<Long> BANNED_URLS = Fields.unsignedLongField("banned_urls");
    }
}
