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

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.tuple.Pair;
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;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.ValueDataMapper;

import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
@Repository
public class HostsWaitFirstRecommendedYDao extends AbstractYDao {

    public HostsWaitFirstRecommendedYDao() {
        super(PREFIX_QUERIES, "hosts_wait_first_recommended");
    }

    public long count() {
        return countAll().queryOne();
    }

    public void insertHost(WebmasterHostId hostId) {
        upsert(
                F.HOST_ID.value(hostId)
        ).execute();
    }

    public void deleteHosts(List<WebmasterHostId> hostIds) {
        delete()
                .where(F.HOST_ID.in(hostIds))
                .execute();
    }

    public void forEachHost(Consumer<WebmasterHostId> consumer) {
        streamReader(F.HOST_ID, consumer);
    }

    public void batchInsert(List<WebmasterHostId> hostIds) {
        batchInsert(MAPPER, hostIds).execute();
    }

    private static final ValueDataMapper<WebmasterHostId> MAPPER = ValueDataMapper.create2(
        Pair.of(F.HOST_ID, Function.identity())
    );

    private static final class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
    }
}
