// SPDX-FileCopyrightText: 2024 Gleb Smirnov <glebsmirnov0708@gmail.com>
//
// SPDX-License-Identifier: MIT

//! This module contains high-level API for
//! stopping actions.

use std::rc::Rc;

use crate::ActionProviderStop;

/// Handle that allows to immediately stop all running actions.
#[derive(Debug)]
pub struct StopHandle<P: ActionProviderStop> {
    /// Action provider reference.
    pub(super) provider: Rc<P>,
    /// Whether to stop all running actions when the handle is dropped.
    pub(super) stop_on_drop: bool,
}

impl<P: ActionProviderStop> StopHandle<P> {
    /// Stops all currently running actions.
    pub fn stop(&self) -> Result<(), P::StopError> {
        self.provider.stop()
    }

    /// Makes the handle stop actions when dropped.
    pub fn stop_on_drop(mut self) -> Self {
        self.stop_on_drop = true;
        self
    }
}

impl<P: ActionProviderStop> Drop for StopHandle<P> {
    fn drop(&mut self) {
        if self.stop_on_drop {
            self.stop().expect("failed to stop actions");
        }
    }
}
