package com.lanyuanxiaoyao.service.sync.metrics;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import java.beans.Transient;
import java.io.Serializable;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 指标实体类
 *
 * @author ZhangJiacheng
 * @date 2022-06-13
 */
public class HttpMetricsRequest implements Serializable {
    private final Map<String, String> metric;
    private final List<Double> values;
    private final List<Long> timestamps;

    private final Lock lock = new ReentrantLock();

    public HttpMetricsRequest(String name, Map<String, String> metrics) {
        this.metric = MapUtil.<String, String>builder()
                .put("__name__", name)
                .build();
        this.metric.putAll(metrics);
        this.values = Collections.synchronizedList(ListUtil.list(true));
        this.timestamps = Collections.synchronizedList(ListUtil.list(true));
    }

    public void addTag(String key, String value) {
        this.metric.put(key, value);
    }

    public void addMetric(Double value) {
        addMetric(value, Instant.now().toEpochMilli());
    }

    public void addMetric(Double value, Long timestamp) {
        synchronized (this) {
            values.add(value);
            timestamps.add(timestamp);
        }
    }

    public void clear() {
        synchronized (this) {
            this.values.clear();
            this.timestamps.clear();
        }
    }

    @Transient
    public boolean isEmpty() {
        return this.values.isEmpty() && this.timestamps.isEmpty();
    }

    @Transient
    public boolean isNonEmpty() {
        return !isEmpty();
    }

    public Map<String, String> getMetric() {
        return metric;
    }

    public List<Double> getValues() {
        return values;
    }

    public List<Long> getTimestamps() {
        return timestamps;
    }

    @Override
    public String toString() {
        return "MetricsItem{" +
               "metrics=" + metric +
               ", values=" + values +
               ", timestamps=" + timestamps +
               '}';
    }
}
