// 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::{ChildMetricMeta, CommonMetricData};

use glean::traits::Counter;

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

/// Developer-facing API for recording counter metrics that are acting as
/// external denominators for rate metrics.
///
/// 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 DenominatorMetric {
    Parent {
        /// The metric's ID. Used for testing and profiler markers.
        /// Denominator metrics canot be labeled, so we only store a
        /// BaseMetricId. If this changes, this should be changed to a
        /// MetricId to distinguish between metrics and sub-metrics.
        id: BaseMetricId,
        inner: glean::private::DenominatorMetric,
    },
    Child(ChildMetricMeta),
}

define_metric_metadata_getter!(DenominatorMetric, DENOMINATOR_MAP);
define_metric_namer!(DenominatorMetric);

impl DenominatorMetric {
    /// The constructor used by automatically generated metrics.
    pub fn new(
        id: BaseMetricId,
        meta: CommonMetricData,
        numerators: Vec<CommonMetricData>,
    ) -> Self {
        if need_ipc() {
            DenominatorMetric::Child(ChildMetricMeta::from_common_metric_data(id, meta))
        } else {
            let inner = glean::private::DenominatorMetric::new(meta, numerators);
            DenominatorMetric::Parent { id, inner }
        }
    }

    #[cfg(test)]
    pub(crate) fn metric_id(&self) -> BaseMetricId {
        match self {
            DenominatorMetric::Parent { id, .. } => *id,
            DenominatorMetric::Child(meta) => meta.id,
        }
    }

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

#[inherent]
impl Counter for DenominatorMetric {
    pub fn add(&self, amount: i32) {
        #[allow(unused)]
        let id = match self {
            DenominatorMetric::Parent { id, inner } => {
                inner.add(amount);
                *id
            }
            DenominatorMetric::Child(meta) => {
                with_ipc_payload(move |payload| {
                    if let Some(v) = payload.denominators.get_mut(&meta.id) {
                        *v += amount;
                    } else {
                        payload.denominators.insert(meta.id, amount);
                    }
                });
                meta.id.into()
            }
        };

        #[cfg(feature = "with_gecko")]
        if gecko_profiler::current_thread_is_being_profiled_for_markers() {
            gecko_profiler::add_marker(
                "Counter::add",
                super::profiler_utils::TelemetryProfilerCategory,
                Default::default(),
                super::profiler_utils::IntLikeMetricMarker::<DenominatorMetric, i32>::new(
                    id.into(),
                    None,
                    amount,
                ),
            );
        }
    }

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

#[inherent]
impl glean::TestGetValue for DenominatorMetric {
    type Output = i32;

    pub fn test_get_value(&self, ping_name: Option<String>) -> Option<i32> {
        match self {
            DenominatorMetric::Parent { inner, .. } => inner.test_get_value(ping_name),
            DenominatorMetric::Child(meta) => {
                panic!(
                    "Cannot get test value for {:?} in non-parent process!",
                    meta.id
                );
            }
        }
    }
}

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

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

        let metric = &metrics::test_only_ipc::an_external_denominator;
        metric.add(1);

        assert_eq!(
            1,
            metric
                .test_get_value(Some("test-ping".to_string()))
                .unwrap()
        );
    }

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

        let parent_metric = &metrics::test_only_ipc::an_external_denominator;
        parent_metric.add(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(42);

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

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

        assert_eq!(
            45,
            parent_metric
                .test_get_value(Some("test-ping".to_string()))
                .unwrap(),
            "Values from the 'processes' should be summed"
        );
    }
}
