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.DoubleAdder;
import java.util.concurrent.atomic.LongAdder;

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

    private final HttpMetricsRequest sizeMetrics;
    private final HttpMetricsRequest perMessageSizeMetrics;

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

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

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

    public MessageSizeSizeMetric(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 MessageSizeSizeMetric(GlobalConfiguration globalConfiguration, String name, Map<String, String> tags) {
        super(globalConfiguration);
        sizeMetrics = new HttpMetricsRequest(
                name + "_total",
                MapUtil.<String, String>builder().putAll(tags).build()
        );
        perMessageSizeMetrics = new HttpMetricsRequest(
                name + "_per_message",
                MapUtil.<String, String>builder().putAll(tags).build()
        );
        setRequests(sizeMetrics, perMessageSizeMetrics);
    }

    public void increment(long size) {
        this.count.increment();
        this.size.add(size);
    }

    @Override
    public void makePoint() {
        double count = this.count.doubleValue();
        double size = this.size.doubleValue();
        if (size != 0 && count != 0) {
            sizeMetrics.addMetric(size);
            perMessageSizeMetrics.addMetric(size / count);
        }
    }

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