/* Code generated by Azure.Iot.Operations.ProtocolCompilerLib v0.10.0.0; DO NOT EDIT. */

use std::collections::HashMap;
use std::time::Duration;

use azure_iot_operations_mqtt::session::SessionManagedClient;
use azure_iot_operations_protocol::application::ApplicationContext;
use azure_iot_operations_protocol::common::aio_protocol_error::AIOProtocolError;
use azure_iot_operations_protocol::rpc_command;

use super::super::common_types::empty_json::EmptyJson;
use super::super::common_types::options::CommandInvokerOptions;
use super::MODEL_ID;
use super::REQUEST_TOPIC_PATTERN;
use super::read_counter_response_payload::ReadCounterResponsePayload;

pub type ReadCounterRequest = rpc_command::invoker::Request<EmptyJson>;
pub type ReadCounterResponse = rpc_command::invoker::Response<ReadCounterResponsePayload>;
pub type ReadCounterRequestBuilderError = rpc_command::invoker::RequestBuilderError;

#[derive(Default)]
/// Builder for [`ReadCounterRequest`]
pub struct ReadCounterRequestBuilder {
    inner_builder: rpc_command::invoker::RequestBuilder<EmptyJson>,
    set_executor_id: bool,
    topic_tokens: HashMap<String, String>,
}

impl ReadCounterRequestBuilder {
    /// Custom user data to set on the request
    pub fn custom_user_data(&mut self, custom_user_data: Vec<(String, String)>) -> &mut Self {
        self.inner_builder.custom_user_data(custom_user_data);
        self
    }

    /// Cloud event for the request
    pub fn cloud_event(
        &mut self,
        cloud_event: Option<rpc_command::invoker::RequestCloudEvent>,
    ) -> &mut Self {
        self.inner_builder.cloud_event(cloud_event);
        self
    }

    /// Topic token keys/values to be replaced into the publish topic of the request message.
    /// A prefix of "ex:" will be prepended to each key before scanning the topic pattern.
    /// Thus, only tokens of the form `{ex:SOMEKEY}` will be replaced.
    pub fn topic_tokens(&mut self, topic_tokens: HashMap<String, String>) -> &mut Self {
        for (k, v) in topic_tokens {
            self.topic_tokens.insert(format!("ex:{k}"), v);
        }
        self
    }

    /// Timeout for the request
    pub fn timeout(&mut self, timeout: Duration) -> &mut Self {
        self.inner_builder.timeout(timeout);
        self
    }

    /// Target executor ID
    pub fn executor_id(&mut self, executor_id: &str) -> &mut Self {
        self.topic_tokens
            .insert("executorId".to_string(), executor_id.to_string());
        self.set_executor_id = true;
        self
    }

    /// Builds a new `ReadCounterRequest`
    ///
    /// # Errors
    /// If a required field has not been initialized
    #[allow(clippy::missing_panics_doc)] // The panic is not possible
    pub fn build(&mut self) -> Result<ReadCounterRequest, ReadCounterRequestBuilderError> {
        if !self.set_executor_id {
            return Err(ReadCounterRequestBuilderError::UninitializedField(
                "executor_id",
            ));
        }

        self.inner_builder.payload(EmptyJson {}).unwrap();

        self.inner_builder.topic_tokens(self.topic_tokens.clone());

        self.inner_builder.build()
    }
}

/// Command Invoker for `readCounter`
pub struct ReadCounterCommandInvoker(rpc_command::Invoker<EmptyJson, ReadCounterResponsePayload>);

impl ReadCounterCommandInvoker {
    /// Creates a new [`ReadCounterCommandInvoker`]
    ///
    /// # Panics
    /// If the DTDL that generated this code was invalid
    pub fn new(
        application_context: ApplicationContext,
        client: SessionManagedClient,
        options: &CommandInvokerOptions,
    ) -> Self {
        let mut invoker_options_builder = rpc_command::invoker::OptionsBuilder::default();
        if let Some(topic_namespace) = &options.topic_namespace {
            invoker_options_builder.topic_namespace(topic_namespace.clone());
        }

        let mut topic_token_map: HashMap<String, String> = options
            .topic_token_map
            .clone()
            .into_iter()
            .map(|(k, v)| (format!("ex:{k}"), v))
            .collect();

        topic_token_map.insert("modelId".to_string(), MODEL_ID.to_string());
        topic_token_map.insert(
            "invokerClientId".to_string(),
            client.client_id().to_string(),
        );
        topic_token_map.insert("commandName".to_string(), "readCounter".to_string());

        let invoker_options = invoker_options_builder
            .request_topic_pattern(REQUEST_TOPIC_PATTERN)
            .command_name("readCounter")
            .topic_token_map(topic_token_map)
            .response_topic_prefix(options.response_topic_prefix.clone())
            .response_topic_suffix(options.response_topic_suffix.clone())
            .build()
            .expect("DTDL schema generated invalid arguments");

        Self(
            rpc_command::Invoker::new(application_context, client, invoker_options)
                .expect("DTDL schema generated invalid arguments"),
        )
    }

    /// Invokes the [`ReadCounterRequest`]
    ///
    /// # Errors
    /// [`AIOProtocolError`] if there is a failure invoking the request
    pub async fn invoke(
        &self,
        request: ReadCounterRequest,
    ) -> Result<ReadCounterResponse, AIOProtocolError> {
        self.0.invoke(request).await
    }

    /// Shutdown the [`ReadCounterCommandInvoker`]. Unsubscribes from the response topic and cancels the receiver loop to drop the receiver and to prevent the task from looping indefinitely.
    ///
    /// Returns Ok(()) on success, otherwise returns [`AIOProtocolError`].
    /// # Errors
    /// [`AIOProtocolError`] of kind [`ClientError`](azure_iot_operations_protocol::common::aio_protocol_error::AIOProtocolErrorKind::ClientError) if the unsubscribe fails or if the unsuback reason code doesn't indicate success.
    pub async fn shutdown(&self) -> Result<(), AIOProtocolError> {
        self.0.shutdown().await
    }
}
