// Copyright 2021 Bloomberg Finance L.P
//
// 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.

#ifndef INCLUDED_BUILDBOXCOMMONMETRICS_METRICTEEGUARD_H
#define INCLUDED_BUILDBOXCOMMONMETRICS_METRICTEEGUARD_H

#include <string>

#include <buildboxcommonmetrics_scopedmetric.h>

namespace buildboxcommon {
namespace buildboxcommonmetrics {

/**
 * MetricTeeGuard
 *
 * It invokes start() and stop() on MetricType upon creation and destruction
 * of the MetricTeeGuard, forwards the value of the metric ValueType to the
 * appropriate collector (provided by the MetricCollectorFactory),
 * and also invokes a custom callback.
 */
template <class MetricType> class MetricTeeGuard {
  private:
    // Infer the type of the value of MetricType
    // by inspecting the type MetricType.value() returns
    MetricType d_metric;
    typedef typename ScopedMetric<MetricType>::ValueType ValueType;

    MetricCollector<ValueType> *d_collector;

    typedef std::function<void(const std::string &, ValueType)>
        WriteMetricCallback;
    WriteMetricCallback d_writeMetricCallback;

  public:
    explicit MetricTeeGuard(const std::string &name,
                            const WriteMetricCallback &writeMetricCallback,
                            MetricCollector<ValueType> *collector = nullptr)
        : d_metric(name), d_collector(collector),
          d_writeMetricCallback(writeMetricCallback)
    {
        d_metric.start();
    }

    ~MetricTeeGuard()
    {
        d_metric.stop();

        const auto name = d_metric.name();
        const auto value = d_metric.value();

        MetricCollectorFactoryUtil::store(name, value, d_collector);

        d_writeMetricCallback(name, value);
    };
};

} // namespace buildboxcommonmetrics
} // namespace buildboxcommon
#endif
