// ------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version: 18.0.0.0
//  
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
namespace Azure.Iot.Operations.EnvoyGenerator
{
    using Azure.Iot.Operations.CodeGeneration;
    using System;
    
    /// <summary>
    /// Class to produce the template output
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
    public partial class RustCommandExecutor : RustCommandExecutorBase
    {
        /// <summary>
        /// Create the template output
        /// </summary>
        public virtual string TransformText()
        {
 // Copyright (c) Microsoft Corporation. 
 // Licensed under the MIT License 
            this.Write("/* Code generated by Azure.Iot.Operations.ProtocolCompilerLib v");
            this.Write(this.ToStringHelper.ToStringWithCulture(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version));
            this.Write(@"; 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;
");
 if (this.respSchema != null) { 
            this.Write("use azure_iot_operations_protocol::common::payload_serialize::PayloadSerialize;\r\n" +
                    "");
 } 
            this.Write("use azure_iot_operations_protocol::rpc_command;\r\n\r\n");
 if (this.reqSchema is CustomTypeName || this.respSchema is CustomTypeName) { 
            this.Write("use super::super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commonNs.GetFolderName(TargetLanguage.Rust)));
            this.Write("::custom_payload::CustomPayload;\r\n");
 } 
 if (this.reqSchema == null || this.respSchema == null || (this.errorResultName != null && this.normalResultSchema == null)) { 
            this.Write("use super::super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commonNs.GetFolderName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.serializerEmptyType.GetFileName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.serializerEmptyType.GetTypeName(TargetLanguage.Rust)));
            this.Write(";\r\n");
 } 
            this.Write("use super::super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commonNs.GetFolderName(TargetLanguage.Rust)));
            this.Write("::options::CommandExecutorOptions;\r\n");
 if (this.reqSchema is CodeName) { 
            this.Write("use super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.reqSchema.GetFileName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.reqSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(";\r\n");
 } 
 if (this.respSchema is CodeName) { 
            this.Write("use super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.respSchema.GetFileName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.respSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(";\r\n");
 } 
 if (this.errorResultName != null) { 
 if (this.normalResultSchema != null) { 
            this.Write("use super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.normalResultSchema.GetFileName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.normalResultSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(";\r\n");
 } 
            this.Write("use super::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.errorResultSchema.GetFileName(TargetLanguage.Rust)));
            this.Write("::");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.errorResultSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(";\r\n");
 } 
            this.Write("\r\npub type ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "request")));
            this.Write(" =\r\n    rpc_command::executor::Request<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.RequestType()));
            this.Write(", ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.ResponseType()));
            this.Write(">;\r\npub type ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response")));
            this.Write(" = rpc_command::executor::Response<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.ResponseType()));
            this.Write(">;\r\npub type ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response", "builder", "error")));
            this.Write(" = rpc_command::executor::ResponseBuilderError;\r\n\r\n/// Builder for [`");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response")));
            this.Write("`]\r\n#[derive(Default)]\r\npub struct ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response", "builder")));
            this.Write(" {\r\n    inner_builder: rpc_command::executor::ResponseBuilder<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.ResponseType()));
            this.Write(">,\r\n}\r\n\r\nimpl ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response", "builder")));
            this.Write(@" {
    /// 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
    }

");
 if (this.respSchema != null) { 
            this.Write("    /// Payload of the response\r\n    ///\r\n    /// # Errors\r\n    /// If the payloa" +
                    "d cannot be serialized\r\n    pub fn payload(\r\n        &mut self,\r\n        payload" +
                    ": ");
            this.Write(this.ToStringHelper.ToStringWithCulture((this.errorResultName != null ? this.normalResultSchema : this.respSchema)?.GetTypeName(TargetLanguage.Rust) ?? this.serializerEmptyType.GetTypeName(TargetLanguage.Rust)));
            this.Write(",\r\n    ) -> Result<&mut Self, AIOProtocolError> {\r\n");
 if (this.errorResultName != null) { 
            this.Write("        self.inner_builder.payload(");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.respSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(" {\r\n");
 if (this.normalResultName != null) { 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.normalResultName.GetFieldName(TargetLanguage.Rust)));
            this.Write(": Some(payload),\r\n");
 } else { 
 foreach (CodeName normalResultField in this.normalResultFields) { 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(normalResultField.GetFieldName(TargetLanguage.Rust)));
            this.Write(": ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.CondSome($"payload.{normalResultField.GetFieldName(TargetLanguage.Rust)}", this.normalRequiredFields.Contains(normalResultField))));
            this.Write(",\r\n");
 } 
 } 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.errorResultName.GetFieldName(TargetLanguage.Rust)));
            this.Write(": None,\r\n        })?;\r\n");
 } else { 
            this.Write("        self.inner_builder.payload(payload)?;\r\n");
 } 
            this.Write("        Ok(self)\r\n    }\r\n\r\n");
 if (this.errorResultName != null) { 
            this.Write("    pub fn error(&mut self, error: ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.errorResultSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(") -> Result<&mut Self, AIOProtocolError> {\r\n        self.inner_builder.payload(");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.respSchema.GetTypeName(TargetLanguage.Rust)));
            this.Write(" {\r\n");
 if (this.normalResultName != null) { 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.normalResultName.GetFieldName(TargetLanguage.Rust)));
            this.Write(": None,\r\n");
 } else { 
 foreach (CodeName normalResultField in this.normalResultFields) { 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(normalResultField.GetFieldName(TargetLanguage.Rust)));
            this.Write(": None,\r\n");
 } 
 } 
            this.Write("            ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.errorResultName.GetFieldName(TargetLanguage.Rust)));
            this.Write(": Some(error),\r\n        })?;\r\n        Ok(self)\r\n    }\r\n\r\n");
 } 
 } 
            this.Write("    /// Builds a new `");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response")));
            this.Write("`\r\n    ///\r\n    /// # Errors\r\n    /// If a required field has not been initialize" +
                    "d\r\n    #[allow(clippy::missing_panics_doc)] // The panic is not possible\r\n    pu" +
                    "b fn build(&mut self) -> Result<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response")));
            this.Write(", ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "response", "builder", "error")));
            this.Write("> {\r\n");
 if (this.respSchema == null) { 
            this.Write("        self.inner_builder.payload(");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.serializerEmptyType.GetAllocator(TargetLanguage.Rust)));
            this.Write(").unwrap();\r\n\r\n");
 } 
            this.Write("        self.inner_builder.build()\r\n    }\r\n}\r\n\r\n/// Command Executor for `");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.AsGiven));
            this.Write("`\r\npub struct ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.componentName.GetTypeName(TargetLanguage.Rust)));
            this.Write("(\r\n    rpc_command::Executor<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.RequestType()));
            this.Write(", ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.ResponseType()));
            this.Write(">,\r\n);\r\n\r\nimpl ");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.componentName.GetTypeName(TargetLanguage.Rust)));
            this.Write("\r\n{\r\n    /// Creates a new [`");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.componentName.GetTypeName(TargetLanguage.Rust)));
            this.Write(@"`]
    ///
    /// # 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(""");
            this.Write(this.ToStringHelper.ToStringWithCulture(MqttTopicTokens.ActionExecutorId));
            this.Write("\".to_string(), client.client_id().to_string());\r\n\r\n        let executor_options =" +
                    " executor_options_builder\r\n            .request_topic_pattern(\"");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.topicPattern));
            this.Write("\")\r\n            .command_name(\"");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.AsGiven));
            this.Write("\")\r\n            .is_idempotent(");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.isIdempotent ? "true" : "false"));
            this.Write(")\r\n            .topic_token_map(topic_token_map)\r\n");
 if (this.serviceGroupId != null) { 
            this.Write("            .service_group_id(\"");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.serviceGroupId));
            this.Write("\".to_string())\r\n");
 } 
            this.Write(@"            .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 [`");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "request")));
            this.Write("`] or [`None`] if there will be no more requests\r\n    ///\r\n    /// # Errors\r\n    " +
                    "/// [`AIOProtocolError`] if there is a failure receiving a request\r\n    pub asyn" +
                    "c fn recv(&mut self) -> Option<Result<");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.commandName.GetTypeName(TargetLanguage.Rust, "request")));
            this.Write(", AIOProtocolError>> {\r\n        self.0.recv().await\r\n    }\r\n\r\n    /// Shutdown th" +
                    "e [`");
            this.Write(this.ToStringHelper.ToStringWithCulture(this.componentName.GetTypeName(TargetLanguage.Rust)));
            this.Write(@"`]. 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
    }
}
");
            return this.GenerationEnvironment.ToString();
        }

    private string RequestType() => this.reqSchema?.GetTypeName(TargetLanguage.Rust) ?? this.serializerEmptyType.GetTypeName(TargetLanguage.Rust);

    private string ResponseType() => this.respSchema?.GetTypeName(TargetLanguage.Rust) ?? this.serializerEmptyType.GetTypeName(TargetLanguage.Rust);

    private string CondSome(string expr, bool doWrap) => doWrap ? $"Some({expr})" : expr;

    }
    #region Base class
    /// <summary>
    /// Base class for this transformation
    /// </summary>
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.TextTemplating", "18.0.0.0")]
    public class RustCommandExecutorBase
    {
        #region Fields
        private global::System.Text.StringBuilder generationEnvironmentField;
        private global::System.CodeDom.Compiler.CompilerErrorCollection errorsField;
        private global::System.Collections.Generic.List<int> indentLengthsField;
        private string currentIndentField = "";
        private bool endsWithNewline;
        private global::System.Collections.Generic.IDictionary<string, object> sessionField;
        #endregion
        #region Properties
        /// <summary>
        /// The string builder that generation-time code is using to assemble generated output
        /// </summary>
        public System.Text.StringBuilder GenerationEnvironment
        {
            get
            {
                if ((this.generationEnvironmentField == null))
                {
                    this.generationEnvironmentField = new global::System.Text.StringBuilder();
                }
                return this.generationEnvironmentField;
            }
            set
            {
                this.generationEnvironmentField = value;
            }
        }
        /// <summary>
        /// The error collection for the generation process
        /// </summary>
        public System.CodeDom.Compiler.CompilerErrorCollection Errors
        {
            get
            {
                if ((this.errorsField == null))
                {
                    this.errorsField = new global::System.CodeDom.Compiler.CompilerErrorCollection();
                }
                return this.errorsField;
            }
        }
        /// <summary>
        /// A list of the lengths of each indent that was added with PushIndent
        /// </summary>
        private System.Collections.Generic.List<int> indentLengths
        {
            get
            {
                if ((this.indentLengthsField == null))
                {
                    this.indentLengthsField = new global::System.Collections.Generic.List<int>();
                }
                return this.indentLengthsField;
            }
        }
        /// <summary>
        /// Gets the current indent we use when adding lines to the output
        /// </summary>
        public string CurrentIndent
        {
            get
            {
                return this.currentIndentField;
            }
        }
        /// <summary>
        /// Current transformation session
        /// </summary>
        public virtual global::System.Collections.Generic.IDictionary<string, object> Session
        {
            get
            {
                return this.sessionField;
            }
            set
            {
                this.sessionField = value;
            }
        }
        #endregion
        #region Transform-time helpers
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void Write(string textToAppend)
        {
            if (string.IsNullOrEmpty(textToAppend))
            {
                return;
            }
            // If we're starting off, or if the previous text ended with a newline,
            // we have to append the current indent first.
            if (((this.GenerationEnvironment.Length == 0) 
                        || this.endsWithNewline))
            {
                this.GenerationEnvironment.Append(this.currentIndentField);
                this.endsWithNewline = false;
            }
            // Check if the current text ends with a newline
            if (textToAppend.EndsWith(global::System.Environment.NewLine, global::System.StringComparison.CurrentCulture))
            {
                this.endsWithNewline = true;
            }
            // This is an optimization. If the current indent is "", then we don't have to do any
            // of the more complex stuff further down.
            if ((this.currentIndentField.Length == 0))
            {
                this.GenerationEnvironment.Append(textToAppend);
                return;
            }
            // Everywhere there is a newline in the text, add an indent after it
            textToAppend = textToAppend.Replace(global::System.Environment.NewLine, (global::System.Environment.NewLine + this.currentIndentField));
            // If the text ends with a newline, then we should strip off the indent added at the very end
            // because the appropriate indent will be added when the next time Write() is called
            if (this.endsWithNewline)
            {
                this.GenerationEnvironment.Append(textToAppend, 0, (textToAppend.Length - this.currentIndentField.Length));
            }
            else
            {
                this.GenerationEnvironment.Append(textToAppend);
            }
        }
        /// <summary>
        /// Write text directly into the generated output
        /// </summary>
        public void WriteLine(string textToAppend)
        {
            this.Write(textToAppend);
            this.GenerationEnvironment.AppendLine();
            this.endsWithNewline = true;
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void Write(string format, params object[] args)
        {
            this.Write(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Write formatted text directly into the generated output
        /// </summary>
        public void WriteLine(string format, params object[] args)
        {
            this.WriteLine(string.Format(global::System.Globalization.CultureInfo.CurrentCulture, format, args));
        }
        /// <summary>
        /// Raise an error
        /// </summary>
        public void Error(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Raise a warning
        /// </summary>
        public void Warning(string message)
        {
            System.CodeDom.Compiler.CompilerError error = new global::System.CodeDom.Compiler.CompilerError();
            error.ErrorText = message;
            error.IsWarning = true;
            this.Errors.Add(error);
        }
        /// <summary>
        /// Increase the indent
        /// </summary>
        public void PushIndent(string indent)
        {
            if ((indent == null))
            {
                throw new global::System.ArgumentNullException("indent");
            }
            this.currentIndentField = (this.currentIndentField + indent);
            this.indentLengths.Add(indent.Length);
        }
        /// <summary>
        /// Remove the last indent that was added with PushIndent
        /// </summary>
        public string PopIndent()
        {
            string returnValue = "";
            if ((this.indentLengths.Count > 0))
            {
                int indentLength = this.indentLengths[(this.indentLengths.Count - 1)];
                this.indentLengths.RemoveAt((this.indentLengths.Count - 1));
                if ((indentLength > 0))
                {
                    returnValue = this.currentIndentField.Substring((this.currentIndentField.Length - indentLength));
                    this.currentIndentField = this.currentIndentField.Remove((this.currentIndentField.Length - indentLength));
                }
            }
            return returnValue;
        }
        /// <summary>
        /// Remove any indentation
        /// </summary>
        public void ClearIndent()
        {
            this.indentLengths.Clear();
            this.currentIndentField = "";
        }
        #endregion
        #region ToString Helpers
        /// <summary>
        /// Utility class to produce culture-oriented representation of an object as a string.
        /// </summary>
        public class ToStringInstanceHelper
        {
            private System.IFormatProvider formatProviderField  = global::System.Globalization.CultureInfo.InvariantCulture;
            /// <summary>
            /// Gets or sets format provider to be used by ToStringWithCulture method.
            /// </summary>
            public System.IFormatProvider FormatProvider
            {
                get
                {
                    return this.formatProviderField ;
                }
                set
                {
                    if ((value != null))
                    {
                        this.formatProviderField  = value;
                    }
                }
            }
            /// <summary>
            /// This is called from the compile/run appdomain to convert objects within an expression block to a string
            /// </summary>
            public string ToStringWithCulture(object objectToConvert)
            {
                if ((objectToConvert == null))
                {
                    throw new global::System.ArgumentNullException("objectToConvert");
                }
                System.Type t = objectToConvert.GetType();
                System.Reflection.MethodInfo method = t.GetMethod("ToString", new System.Type[] {
                            typeof(System.IFormatProvider)});
                if ((method == null))
                {
                    return objectToConvert.ToString();
                }
                else
                {
                    return ((string)(method.Invoke(objectToConvert, new object[] {
                                this.formatProviderField })));
                }
            }
        }
        private ToStringInstanceHelper toStringHelperField = new ToStringInstanceHelper();
        /// <summary>
        /// Helper to produce culture-oriented representation of an object as a string
        /// </summary>
        public ToStringInstanceHelper ToStringHelper
        {
            get
            {
                return this.toStringHelperField;
            }
        }
        #endregion
    }
    #endregion
}
