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

use std::collections::HashMap;

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::common::payload_serialize::PayloadSerialize;
use azure_iot_operations_protocol::rpc_command;

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

pub type ReadCounterRequest = rpc_command::executor::Request<EmptyJson, ReadCounterResponsePayload>;
pub type ReadCounterResponse = rpc_command::executor::Response<ReadCounterResponsePayload>;
pub type ReadCounterResponseBuilderError = rpc_command::executor::ResponseBuilderError;

/// Builder for [`ReadCounterResponse`]
#[derive(Default)]
pub struct ReadCounterResponseBuilder {
    inner_builder: rpc_command::executor::ResponseBuilder<ReadCounterResponsePayload>,
}

impl ReadCounterResponseBuilder {
    /// Custom user data to set on the response
    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 response
    pub fn cloud_event(
        &mut self,
        cloud_event: Option<rpc_command::executor::ResponseCloudEvent>,
    ) -> &mut Self {
        self.inner_builder.cloud_event(cloud_event);
        self
    }

    /// Payload of the response
    ///
    /// # Errors
    /// If the payload cannot be serialized
    pub fn payload(
        &mut self,
        payload: ReadCounterResponsePayload,
    ) -> Result<&mut Self, AIOProtocolError> {
        self.inner_builder.payload(payload)?;
        Ok(self)
    }

    /// Builds a new `ReadCounterResponse`
    ///
    /// # 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<ReadCounterResponse, ReadCounterResponseBuilderError> {
        self.inner_builder.build()
    }
}

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

impl ReadCounterCommandExecutor {
    /// Creates a new [`ReadCounterCommandExecutor`]
    ///
    /// # Panics
    /// If the DTDL that generated this code was invalid
    pub fn new(
        application_context: ApplicationContext,
        client: SessionManagedClient,
        options: &CommandExecutorOptions,
    ) -> Self {
        let mut executor_options_builder = rpc_command::executor::OptionsBuilder::default();
        if let Some(topic_namespace) = &options.topic_namespace {
            executor_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("executorId".to_string(), client.client_id().to_string());
        topic_token_map.insert("commandName".to_string(), "readCounter".to_string());

        let executor_options = executor_options_builder
            .request_topic_pattern(REQUEST_TOPIC_PATTERN)
            .command_name("readCounter")
            .is_idempotent(false)
            .topic_token_map(topic_token_map)
            .build()
            .expect("DTDL schema generated invalid arguments");

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

    /// Receive the next [`ReadCounterRequest`] or [`None`] if there will be no more requests
    ///
    /// # Errors
    /// [`AIOProtocolError`] if there is a failure receiving a request
    pub async fn recv(&mut self) -> Option<Result<ReadCounterRequest, AIOProtocolError>> {
        self.0.recv().await
    }

    /// Shutdown the [`ReadCounterCommandExecutor`]. Unsubscribes from the request topic.
    ///
    /// 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(&mut self) -> Result<(), AIOProtocolError> {
        self.0.shutdown().await
    }
}
