package com.lanyuanxiaoyao.service.executor.metrics;

import cn.hutool.core.util.StrUtil;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.flink.metrics.MetricConfig;
import org.apache.flink.metrics.reporter.InterceptInstantiationViaReflection;
import org.apache.flink.metrics.reporter.MetricReporterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.lanyuanxiaoyao.service.executor.metrics.VictoriaMetricsOptions.*;

/**
 * @author ZhangJiacheng
 * @date 2022-06-22
 */
@InterceptInstantiationViaReflection(
        reporterClassName = "com.eshore.odcp.hudi.connector.utils.executor.metrics.VictoriaMetricsReporter")
public class VictoriaMetricsReporterFactory implements MetricReporterFactory {
    private static final Logger logger = LoggerFactory.getLogger(VictoriaMetricsReporterFactory.class);

    @Override
    public VictoriaMetricsReporter createMetricReporter(Properties properties) {
        MetricConfig metricConfig = (MetricConfig) properties;
        String endpoint = metricConfig.getString(ENDPOINT.key(), ENDPOINT.defaultValue());
        int timeout = metricConfig.getInteger(TIMEOUT.key(), TIMEOUT.defaultValue());
        String tagsText = metricConfig.getString(TAGS.key(), TAGS.defaultValue());
        Boolean enableAuth = metricConfig.getBoolean(ENABLE_AUTH.key(), ENABLE_AUTH.defaultValue());
        String authUsername = metricConfig.getString(AUTH_USERNAME.key(), AUTH_USERNAME.defaultValue());
        String authPassword = metricConfig.getString(AUTH_PASSWORD.key(), AUTH_PASSWORD.defaultValue());

        Map<String, String> tags = new HashMap<>(10);
        if (StrUtil.isNotBlank(tagsText)) {
            for (String item : tagsText.split(";")) {
                String[] parsed = item.split("=");
                tags.put(parsed[0], parsed[1]);
            }
        }
        logger.info("Create victoria metric reporter for endpoint {} timeout: {}, tags: {}, enable_auth: {}, auth_username: {}, auth_password: {}", endpoint, timeout, tags, enableAuth, authUsername, authPassword);
        return new VictoriaMetricsReporter(endpoint, timeout, tags, enableAuth, authUsername, authPassword);
    }
}
