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

import java.util.Collection;
import java.util.Objects;

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;

/**
 * @author leonidrom
 */
@Repository
public class HostRegionsLimitYDao extends AbstractYDao {
    private static final String TABLE_NAME = "host_regions_limit";
    private static final int DEFAULT_LIMIT = 1;

    private static final ValueDataMapper<Pair<WebmasterHostId, Integer>> INSERT_VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_ID, Pair::getLeft),
            Pair.of(F.LIMIT, Pair::getRight)
    );

    public HostRegionsLimitYDao() {
        super(PREFIX_REGION, TABLE_NAME);
    }

    public void storeLimit(WebmasterHostId hostId, int limit)  {
        upsert(F.HOST_ID.value(hostId), F.LIMIT.value(limit)).execute();
    }

    public void storeLimits(Collection<Pair<WebmasterHostId, Integer>> pairs) {
        batchInsert(INSERT_VALUE_MAPPER, pairs).execute();
    }

    public int getLimit(WebmasterHostId hostId) {
        return Objects.requireNonNullElse(select(F.LIMIT).where(F.HOST_ID.eq(hostId)).queryOne(), DEFAULT_LIMIT);
    }

    private interface F {
        Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        Field<Integer> LIMIT = Fields.intField("limit").makeOptional();
    }
}
