package ru.yandex.webmaster3.monitoring.solomon.dao;

import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.stereotype.Repository;

import ru.yandex.webmaster3.monitoring.solomon.SolomonTriggerProperty;
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;


/**
 * @author kravchenko99
 * @date 11/25/20
 */

@Repository
public class WebmasterTriggerPropertiesYDao extends AbstractYDao {
    private static final String TABLE_NAME = "webmaster_trigger_properties";

    public WebmasterTriggerPropertiesYDao() {
        super(PREFIX_MONITORING, TABLE_NAME);
    }

    public List<SolomonTriggerProperty> listAllProperties() {
        return queryForList(select(MAPPER), MAPPER);
    }

    public void batchInsert(List<SolomonTriggerProperty> properties) {
        execute(batchInsert(VALUE_DATA_MAPPER, properties));
    }

    private static final DataMapper<SolomonTriggerProperty> MAPPER = DataMapper.create(
            F.LABELS, F.PROPERTY_NAME, F.PROPERTY_VALUE, SolomonTriggerProperty::new
    );

    private static final ValueDataMapper<SolomonTriggerProperty> VALUE_DATA_MAPPER = ValueDataMapper.create(
            Pair.of(F.LABELS, data -> F.LABELS.get(data.getLabels())),
            Pair.of(F.PROPERTY_NAME, data -> F.PROPERTY_NAME.get(data.getName())),
            Pair.of(F.PROPERTY_VALUE, data -> F.PROPERTY_VALUE.get(data.getValue()))
    );

    private interface F {
        TypeReference<Map<String, String>> MAP = new TypeReference<>() {
        };
        Field<String> PROPERTY_NAME = Fields.stringField("property_name");
        Field<Map<String, String>> LABELS = Fields.jsonField("labels", MAP);
        Field<JsonNode> PROPERTY_VALUE = Fields.jsonField2("property_value", JsonNode.class);
    }
}
