package com.lanyuanxiaoyao.service.sync.utils;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import com.lanyuanxiaoyao.service.common.Constants;
import com.lanyuanxiaoyao.service.common.entity.FlinkJob;
import com.lanyuanxiaoyao.service.common.entity.TableMeta;
import com.lanyuanxiaoyao.service.sync.configuration.GlobalConfiguration;
import com.lanyuanxiaoyao.service.sync.metrics.AbstractMetric;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 指标工具
 *
 * @author ZhangJiacheng
 * @date 2022-06-12
 */
public class MetricsUtils implements Serializable {
    private static final Logger logger = LoggerFactory.getLogger(MetricsUtils.class);

    public static Map<String, String> commonTags(FlinkJob job, TableMeta meta) {
        return MapUtil.<String, String>builder()
                .put(Constants.METRICS_LABEL_FLINK_JOB_ID, job.getId().toString())
                .put(Constants.METRICS_LABEL_FLINK_JOB_NAME, job.getName())
                .put(Constants.METRICS_LABEL_SCHEMA, meta.getSchema())
                .put(Constants.METRICS_LABEL_TABLE, meta.getTable())
                .put(Constants.METRICS_LABEL_ALIAS, meta.getAlias())
                .build();
    }

    @SafeVarargs
    public static <T extends AbstractMetric> void createMakePointTimer(GlobalConfiguration globalConfiguration, T... metrics) {
        createMakePointTimer(globalConfiguration, ListUtil.toList(metrics));
    }

    public static <T extends AbstractMetric> void createMakePointTimer(GlobalConfiguration globalConfiguration, List<T> metrics) {
        logger.info("Create timer: {}", metrics);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                for (AbstractMetric metric : metrics) {
                    metric.makePoint(true, globalConfiguration.getMetricPublishBatch());
                }
            }
        }, globalConfiguration.getMetricPublishDelay(), globalConfiguration.getMetricPublishPeriod());
    }

    @SafeVarargs
    public static <T extends AbstractMetric> void publishAllMetrics(T... metrics) {
        publishAllMetrics(ListUtil.toList(metrics));
    }

    public static <T extends AbstractMetric> void publishAllMetrics(List<T> metrics) {
        for (AbstractMetric metric : metrics) {
            metric.publish();
        }
    }
}
