package com.atlassian.bitbucket.mesh.metrics;

import com.google.common.collect.ImmutableList;
import io.micrometer.core.instrument.Tag;

import java.util.Comparator;
import java.util.List;

public class MetricsConstants {

    //Prefixes for various types of metrics
    public static final String PREFIX_GRPC = "grpc.";
    public static final String PREFIX_OPERATION = "operation.";
    public static final String PREFIX_PACK_CACHE = "packCache.";
    public static final String PREFIX_REPAIR = "repair.";
    public static final String PREFIX_THROTTLING = "throttling.";

    //Summary names
    public static final String SUMMARY_RPC_MESSAGES = "rpc.messages";

    //Support for tag sorting
    public static final Comparator<Tag> TAG_COMPARATOR = new TagComparator();

    //Tag names used to parameterize Metrics
    public static final String TAG_METHOD = "rpc-method";
    public static final String TAG_SERVICE = "rpc-service";
    public static final String TAG_THROTTLED_RESOURCE = "throttled-resource";

    //Timer names
    public static final String TIMER_RPC_CALLS = "rpc.calls";

    private static class TagComparator implements Comparator<Tag> {

        private final List<String> TAG_SORT_ORDER = ImmutableList.of(TAG_SERVICE, TAG_METHOD, TAG_THROTTLED_RESOURCE);

        @Override
        public int compare(Tag tag1, Tag tag2) {
            for (String sortedTag : TAG_SORT_ORDER) {
                if (sortedTag.equals(tag1.getKey())) {
                    //Encountered tag1 first
                    return -1;
                }
                if (sortedTag.equals(tag2.getKey())) {
                    //Encountered tag2 first
                    return 1;
                }
            }
            //Neither tag1, nor tag2 are configured as sorted tags. The order doesn't matter
            return 0;
        }
    }
}
