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

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

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.crawl.UserCrawlSettings;
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;
import ru.yandex.webmaster3.storage.util.ydb.querybuilder.typesafe.ValueDataMapper;


/**
 * Created by kravchenko99 on 26.01.21.
 */
@Repository
public class UserCrawlSettingsYDao extends AbstractYDao {

    private static final String TABLE_NAME = "user_crawl_settings";

    public UserCrawlSettingsYDao() {
        super(PREFIX_CRAWL, TABLE_NAME);
    }

    public void updateSettings(WebmasterHostId hostId, UserCrawlSettings settings) {
        upsert(
                F.HOST_ID.value(hostId),
                F.USE_DEFAULTS.value(settings.isUseDefaults()),
                F.MULTIPLIER.value(settings.getMultiplier())
        ).execute();
    }

    public UserCrawlSettings getSettings(WebmasterHostId hostId) {
        return select(MAPPER)
                .where(F.HOST_ID.eq(hostId))
                .queryOne();
    }

    public void forEach(Consumer<Pair<WebmasterHostId, UserCrawlSettings>> consumer) {
        streamReader(MAPPER_WITH_HOST_ID, consumer);
    }

    public void batchInsert(List<Pair<WebmasterHostId, UserCrawlSettings>> items) {
        batchInsert(VALUE_MAPPER, items).execute();
    }

    private static final DataMapper<UserCrawlSettings> MAPPER = DataMapper.create(F.USE_DEFAULTS, F.MULTIPLIER, UserCrawlSettings::new);
    private static final ValueDataMapper<Pair<WebmasterHostId, UserCrawlSettings>> VALUE_MAPPER = ValueDataMapper.create2(
            Pair.of(F.HOST_ID, Pair::getKey),
            Pair.of(F.USE_DEFAULTS, x -> x.getValue().isUseDefaults()),
            Pair.of(F.MULTIPLIER, x -> x.getValue().getMultiplier())
    );

    private static final DataMapper<Pair<WebmasterHostId, UserCrawlSettings>> MAPPER_WITH_HOST_ID = DataMapper.create(F.HOST_ID, MAPPER, Pair::of);

    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<Boolean> USE_DEFAULTS = Fields.boolField("use_defaults");
        static final Field<Double> MULTIPLIER = Fields.doubleField("multiplier");
    }
}
