/* Code generated by Azure.Iot.Operations.ProtocolCompilerLib v1.0.0.0; DO NOT EDIT. */

use std::collections::HashMap;
use std::error::Error;
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, AIOProtocolErrorKind,
};
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::CommandInvokerOptions;
use super::delete_thing_model_version_input_arguments::DeleteThingModelVersionInputArguments;
use super::delete_thing_model_version_response_schema::DeleteThingModelVersionResponseSchema;
use super::thing_model_extension_error::ThingModelExtensionError;

pub type DeleteThingModelVersionRequest =
    rpc_command::invoker::Request<DeleteThingModelVersionInputArguments>;
pub type DeleteThingModelVersionResponse = rpc_command::invoker::Response<EmptyJson>;
pub type DeleteThingModelVersionResponseError =
    rpc_command::invoker::Response<ThingModelExtensionError>;
pub type DeleteThingModelVersionRequestBuilderError = rpc_command::invoker::RequestBuilderError;

#[derive(Default)]
/// Builder for [`DeleteThingModelVersionRequest`]
pub struct DeleteThingModelVersionRequestBuilder {
    inner_builder: rpc_command::invoker::RequestBuilder<DeleteThingModelVersionInputArguments>,
    topic_tokens: HashMap<String, String>,
}

impl DeleteThingModelVersionRequestBuilder {
    /// 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
    }

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

    /// Builds a new `DeleteThingModelVersionRequest`
    ///
    /// # 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<DeleteThingModelVersionRequest, DeleteThingModelVersionRequestBuilderError> {
        self.inner_builder.topic_tokens(self.topic_tokens.clone());

        self.inner_builder.build()
    }
}

/// Command Invoker for `deleteThingModelVersion`
pub struct DeleteThingModelVersionActionInvoker(
    rpc_command::Invoker<
        DeleteThingModelVersionInputArguments,
        DeleteThingModelVersionResponseSchema,
    >,
);

impl DeleteThingModelVersionActionInvoker {
    /// Creates a new [`DeleteThingModelVersionActionInvoker`]
    ///
    /// # 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(
            "invokerClientId".to_string(),
            client.client_id().to_string(),
        );

        let invoker_options = invoker_options_builder
            .request_topic_pattern("aio/registry/thingModelExtension/delete/thingmodelgroups/thingmodels/{ex:thingModelId}/versions/{ex:versionId}")
            .command_name("deleteThingModelVersion")
            .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 [`DeleteThingModelVersionRequest`]
    ///
    /// # Errors
    /// [`AIOProtocolError`] if there is a failure invoking the request
    pub async fn invoke(
        &self,
        request: DeleteThingModelVersionRequest,
    ) -> Result<
        Result<DeleteThingModelVersionResponse, DeleteThingModelVersionResponseError>,
        AIOProtocolError,
    > {
        let response = self.0.invoke(request).await;
        match response {
            Ok(response) => {
                if let Some(error) = response.payload.error {
                    Ok(Err(DeleteThingModelVersionResponseError {
                        payload: error,
                        content_type: response.content_type,
                        format_indicator: response.format_indicator,
                        custom_user_data: response.custom_user_data,
                        timestamp: response.timestamp,
                        executor_id: response.executor_id,
                    }))
                } else {
                    Ok(Ok(DeleteThingModelVersionResponse {
                        payload: EmptyJson {},
                        content_type: response.content_type,
                        format_indicator: response.format_indicator,
                        custom_user_data: response.custom_user_data,
                        timestamp: response.timestamp,
                        executor_id: response.executor_id,
                    }))
                }
            }
            Err(err) => Err(err),
        }
    }

    /// Shutdown the [`DeleteThingModelVersionActionInvoker`]. 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
    }
}
