/**
 * Copyright Pravega Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.pravega.shared.metrics;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import lombok.Getter;

/**
 * The various metrics that can be generated by the client.
 */
public enum ClientMetricKeys {

    /**
     * Metric to track the amount of time in ms to perform an append to the Segment store.
     */
    CLIENT_APPEND_LATENCY("client.segment.append_latency_ms"),
    /**
     * Metric to track the append block size for a given segment writer.
     */
    CLIENT_APPEND_BLOCK_SIZE("client.segment.append_block_size"),
    /**
     * Metric to track the number of appends which have not been acknowledged by the segment store.
     */
    CLIENT_OUTSTANDING_APPEND_COUNT("client.segment.outstanding_append_count");

    @VisibleForTesting
    @Getter
    private final String metricKey;

    ClientMetricKeys(String metricKey) {
        StringBuilder sb = new StringBuilder("pravega");
        sb.append(".");
        this.metricKey = sb.append(metricKey).toString();
    }

    /**
     * Create a metric string based on metric key and associated tags.
     * If no tags are supplied the origninal metric key is returned.
     *
     * @param tags the tag(s) associated with the metric key.
     * @return the metric.
     */
    public String metric(String... tags) {
        if (tags == null || tags.length == 0) {
            return metricKey;
        } else { //if tag is supplied, append tag value to form metric.
            StringBuilder sb = new StringBuilder(metricKey);
            Preconditions.checkArgument((tags.length % 2) == 0, "Tags is a set of key/value pair so the size must be even: %s", tags.length);
            for (int i = 0; i < tags.length; i += 2) {
                Preconditions.checkArgument(!Strings.isNullOrEmpty(tags[i]) && !Strings.isNullOrEmpty(tags[i + 1]),
                                            "Tag name or value cannot be empty or null");
                sb.append('.').append(tags[i + 1]);
            }
            return sb.toString();
        }
    }
}
