package com.lanyuanxiaoyao.service.sync.metrics;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
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.utils.MetricsUtils;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;

/**
 * 基础类
 *
 * @author ZhangJiacheng
 * @date 2022-06-13
 */
public class CountMetric extends AbstractMetric {
    private final LongAdder count = new LongAdder();

    private final HttpMetricsRequest countMetrics;

    public CountMetric(GlobalConfiguration globalConfiguration, String name) {
        this(globalConfiguration, name, MapUtil.empty());
    }

    public CountMetric(GlobalConfiguration globalConfiguration, String name, FlinkJob job, TableMeta meta) {
        this(globalConfiguration, name, MapUtil.builder(MetricsUtils.commonTags(job, meta)).build());
    }

    public CountMetric(GlobalConfiguration globalConfiguration, String name, FlinkJob job, TableMeta meta, String extraTagKey, String extraTagValue) {
        this(globalConfiguration, name, job, meta, MapUtil.of(extraTagKey, extraTagValue));
    }

    public CountMetric(GlobalConfiguration globalConfiguration, String name, FlinkJob job, TableMeta meta, Map<String, String> tags) {
        this(globalConfiguration, name, MapUtil.builder(MetricsUtils.commonTags(job, meta))
                .putAll(tags)
                .build());
    }

    public CountMetric(GlobalConfiguration globalConfiguration, String name, Map<String, String> tags) {
        super(globalConfiguration);
        countMetrics = new HttpMetricsRequest(
                name + "_count",
                MapUtil.<String, String>builder().putAll(tags).build()
        );
        setRequests(countMetrics);
    }

    public void increment() {
        count.increment();
    }

    @Override
    public void makePoint() {
        double count = this.count.doubleValue();
        if (count != 0) {
            countMetrics.addMetric(count);
        }
    }

    @Override
    public List<HttpMetricsRequest> getMetrics() {
        return ListUtil.toList(countMetrics);
    }
}
