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

import org.springframework.stereotype.Repository;
import ru.yandex.webmaster3.core.util.enums.EnumResolver;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.storage.crawl.RotorSettings;
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 java.util.function.Consumer;

/**
 * @author leonidrom
 */
@Repository
public class RotorSettingsYDao extends AbstractYDao {
    private static final String TABLE_NAME = "rotor_settings";

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

    public void updateSettings(RotorSettings settings) {
        upsert(
                F.HOST_ID.value(settings.hostId()),
                F.RENDER_SETTINGS.value(settings.renderSettings())
        ).execute();
    }

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

    public void forEach(Consumer<RotorSettings> consumer) {
        streamReader(MAPPER, consumer);
    }

    private static final DataMapper<RotorSettings> MAPPER = DataMapper.create(F.HOST_ID, F.RENDER_SETTINGS, RotorSettings::new);

    private static class F {
        static final Field<WebmasterHostId> HOST_ID = Fields.hostIdField("host_id");
        static final Field<RotorSettings.RenderSettings> RENDER_SETTINGS = Fields.stringEnumField(
                "render_settings", RotorSettings.RenderSettings.R);
    }
}
