// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use inherent::inherent;

use super::CommonMetricData;

use glean::traits::Numerator;
use glean::Rate;

use crate::ipc::{need_ipc, with_ipc_payload};
use crate::private::MetricId;

/// Developer-facing API for recording rate metrics with external denominators.
///
/// Instances of this class type are automatically generated by the parsers
/// at build time, allowing developers to record values that were previously
/// registered in the metrics.yaml file.
#[derive(Clone)]
pub enum NumeratorMetric {
    Parent {
        /// The metric's ID.
        ///
        /// **TEST-ONLY** - Do not use unless gated with `#[cfg(test)]`.
        id: MetricId,
        inner: glean::private::NumeratorMetric,
    },
    Child(NumeratorMetricIpc),
}
#[derive(Clone, Debug)]
pub struct NumeratorMetricIpc(MetricId);

impl NumeratorMetric {
    /// The public constructor used by automatically generated metrics.
    pub fn new(id: MetricId, meta: CommonMetricData) -> Self {
        if need_ipc() {
            NumeratorMetric::Child(NumeratorMetricIpc(id))
        } else {
            let inner = glean::private::NumeratorMetric::new(meta);
            NumeratorMetric::Parent { id, inner }
        }
    }

    #[cfg(test)]
    pub(crate) fn metric_id(&self) -> MetricId {
        match self {
            NumeratorMetric::Parent { id, .. } => *id,
            NumeratorMetric::Child(c) => c.0,
        }
    }

    #[cfg(test)]
    pub(crate) fn child_metric(&self) -> Self {
        match self {
            NumeratorMetric::Parent { id, .. } => NumeratorMetric::Child(NumeratorMetricIpc(*id)),
            NumeratorMetric::Child(_) => panic!("Can't get a child metric from a child metric"),
        }
    }
}

#[inherent]
impl Numerator for NumeratorMetric {
    pub fn add_to_numerator(&self, amount: i32) {
        match self {
            NumeratorMetric::Parent { inner, .. } => {
                inner.add_to_numerator(amount);
            }
            NumeratorMetric::Child(c) => {
                with_ipc_payload(move |payload| {
                    if let Some(v) = payload.numerators.get_mut(&c.0) {
                        *v += amount;
                    } else {
                        payload.numerators.insert(c.0, amount);
                    }
                });
            }
        }
    }

    pub fn test_get_value<'a, S: Into<Option<&'a str>>>(&self, ping_name: S) -> Option<Rate> {
        let ping_name = ping_name.into().map(|s| s.to_string());
        match self {
            NumeratorMetric::Parent { inner, .. } => inner.test_get_value(ping_name),
            NumeratorMetric::Child(c) => {
                panic!("Cannot get test value for {:?} in non-parent process!", c.0);
            }
        }
    }

    pub fn test_get_num_recorded_errors(&self, error: glean::ErrorType) -> i32 {
        match self {
            NumeratorMetric::Parent { inner, .. } => inner.test_get_num_recorded_errors(error),
            NumeratorMetric::Child(c) => {
                panic!(
                    "Cannot get the number of recorded errors for {:?} in non-parent process!",
                    c.0
                );
            }
        }
    }
}

#[cfg(test)]
mod test {
    use crate::{common_test::*, ipc, metrics};

    #[test]
    fn sets_numerator_value_parent() {
        let _lock = lock_test();

        let metric = &metrics::test_only_ipc::rate_with_external_denominator;
        metric.add_to_numerator(1);

        assert_eq!(1, metric.test_get_value("store1").unwrap().numerator);
    }

    #[test]
    fn sets_numerator_value_child() {
        let _lock = lock_test();

        let parent_metric = &metrics::test_only_ipc::rate_with_external_denominator;
        parent_metric.add_to_numerator(3);

        {
            // scope for need_ipc RAII
            let child_metric = parent_metric.child_metric();
            let _raii = ipc::test_set_need_ipc(true);
            let metric_id = child_metric.metric_id();

            child_metric.add_to_numerator(42);

            ipc::with_ipc_payload(move |payload| {
                assert!(
                    42 == *payload.numerators.get(&metric_id).unwrap(),
                    "Stored the correct value in the ipc payload"
                );
            });
        }

        assert!(
            false == ipc::need_ipc(),
            "RAII dropped, should not need ipc any more"
        );
        assert!(ipc::replay_from_buf(&ipc::take_buf().unwrap()).is_ok());

        assert!(
            45 == parent_metric.test_get_value("store1").unwrap().numerator,
            "Values from the 'processes' should be summed"
        );
    }
}
