# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#
# Code generated by aaz-dev-tools
# --------------------------------------------------------------------------------------------

# pylint: skip-file
# flake8: noqa

from azure.cli.core.aaz import *


class Update(AAZCommand):
    """Update operation to create or update the run command.
    """

    _aaz_info = {
        "version": "2024-11-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.compute/virtualmachines/{}/runcommands/{}", "2024-11-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = True

    AZ_SUPPORT_GENERIC_UPDATE = True

    def _handler(self, command_args):
        super()._handler(command_args)
        return self.build_lro_poller(self._execute_operations, self._output)

    _args_schema = None

    @classmethod
    def _build_arguments_schema(cls, *args, **kwargs):
        if cls._args_schema is not None:
            return cls._args_schema
        cls._args_schema = super()._build_arguments_schema(*args, **kwargs)

        # define Arg Group ""

        _args_schema = cls._args_schema
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.run_command_name = AAZStrArg(
            options=["-n", "--name", "--run-command-name"],
            help="The name of the VirtualMachineRunCommand",
            required=True,
            id_part="child_name_1",
        )
        _args_schema.vm_name = AAZStrArg(
            options=["--vm-name"],
            help="The name of the VirtualMachine",
            required=True,
            id_part="name",
        )
        _args_schema.async_execution = AAZBoolArg(
            options=["--async-execution"],
            help="Optional. If set to true, provisioning will complete as soon as the script starts and will not wait for script to complete.",
            nullable=True,
        )
        _args_schema.error_blob_uri = AAZStrArg(
            options=["--error-blob-uri"],
            help="Specify the Azure storage blob where script error stream will be uploaded.",
            nullable=True,
        )
        _args_schema.output_blob_uri = AAZStrArg(
            options=["--output-blob-uri"],
            help="Specify the Azure storage blob (SAS URI) where script output stream will be uploaded.",
            nullable=True,
        )
        _args_schema.parameters = AAZListArg(
            options=["--parameters"],
            help="The parameters used by the script.",
            nullable=True,
        )
        _args_schema.protected_parameters = AAZListArg(
            options=["--protected-parameters"],
            help="The parameters used by the script.",
            nullable=True,
        )
        _args_schema.run_as_password = AAZStrArg(
            options=["--run-as-password"],
            help="Password if needed for using run-as-user parameter. It will be encrypted and not logged",
            nullable=True,
        )
        _args_schema.run_as_user = AAZStrArg(
            options=["--run-as-user"],
            help="By default script process runs under system/root user. Specify custom user to host the process.",
            nullable=True,
        )
        _args_schema.command_id = AAZStrArg(
            options=["--command-id"],
            help="Specifies a commandId of predefined built-in script.",
            nullable=True,
        )
        _args_schema.script = AAZStrArg(
            options=["--script"],
            help="Specifies the script content to be executed on the VM.",
            nullable=True,
        )
        _args_schema.script_uri = AAZStrArg(
            options=["--script-uri"],
            help="Specifies the script download location. It can be either SAS URI of an Azure storage blob with read access or public URI.",
            nullable=True,
        )
        _args_schema.timeout_in_seconds = AAZIntArg(
            options=["--timeout-in-seconds"],
            help="The timeout in seconds to execute the run command.",
            nullable=True,
        )
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            help="Space-separated tags: key[=value] [key[=value] ...].",
            nullable=True,
        )

        parameters = cls._args_schema.parameters
        parameters.Element = AAZObjectArg(
            nullable=True,
        )
        cls._build_args_run_command_input_parameter_update(parameters.Element)

        protected_parameters = cls._args_schema.protected_parameters
        protected_parameters.Element = AAZObjectArg(
            nullable=True,
        )
        cls._build_args_run_command_input_parameter_update(protected_parameters.Element)

        tags = cls._args_schema.tags
        tags.Element = AAZStrArg(
            nullable=True,
        )

        # define Arg Group "Properties"

        # define Arg Group "Source"
        return cls._args_schema

    _args_run_command_input_parameter_update = None

    @classmethod
    def _build_args_run_command_input_parameter_update(cls, _schema):
        if cls._args_run_command_input_parameter_update is not None:
            _schema.name = cls._args_run_command_input_parameter_update.name
            _schema.value = cls._args_run_command_input_parameter_update.value
            return

        cls._args_run_command_input_parameter_update = AAZObjectArg(
            nullable=True,
        )

        run_command_input_parameter_update = cls._args_run_command_input_parameter_update
        run_command_input_parameter_update.name = AAZStrArg(
            options=["name"],
            help="The run command parameter name.",
        )
        run_command_input_parameter_update.value = AAZStrArg(
            options=["value"],
            help="The run command parameter value.",
        )

        _schema.name = cls._args_run_command_input_parameter_update.name
        _schema.value = cls._args_run_command_input_parameter_update.value

    _args_run_command_managed_identity_update = None

    @classmethod
    def _build_args_run_command_managed_identity_update(cls, _schema):
        if cls._args_run_command_managed_identity_update is not None:
            _schema.client_id = cls._args_run_command_managed_identity_update.client_id
            _schema.object_id = cls._args_run_command_managed_identity_update.object_id
            return

        cls._args_run_command_managed_identity_update = AAZObjectArg(
            nullable=True,
        )

        run_command_managed_identity_update = cls._args_run_command_managed_identity_update
        run_command_managed_identity_update.client_id = AAZStrArg(
            options=["client-id"],
            help="Client Id (GUID value) of the user-assigned managed identity. ObjectId should not be used if this is provided.",
            nullable=True,
        )
        run_command_managed_identity_update.object_id = AAZStrArg(
            options=["object-id"],
            help="Object Id (GUID value) of the user-assigned managed identity. ClientId should not be used if this is provided.",
            nullable=True,
        )

        _schema.client_id = cls._args_run_command_managed_identity_update.client_id
        _schema.object_id = cls._args_run_command_managed_identity_update.object_id

    def _execute_operations(self):
        self.pre_operations()
        self.VirtualMachineRunCommandsGetByVirtualMachine(ctx=self.ctx)()
        self.pre_instance_update(self.ctx.vars.instance)
        self.InstanceUpdateByJson(ctx=self.ctx)()
        self.InstanceUpdateByGeneric(ctx=self.ctx)()
        self.post_instance_update(self.ctx.vars.instance)
        yield self.VirtualMachineRunCommandsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    @register_callback
    def pre_instance_update(self, instance):
        pass

    @register_callback
    def post_instance_update(self, instance):
        pass

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
        return result

    class VirtualMachineRunCommandsGetByVirtualMachine(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [200]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "GET"

        @property
        def error_format(self):
            return "ODataV4Format"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "runCommandName", self.ctx.args.run_command_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
                **self.serialize_url_param(
                    "vmName", self.ctx.args.vm_name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2024-11-01",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        def on_200(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200
            )

        _schema_on_200 = None

        @classmethod
        def _build_schema_on_200(cls):
            if cls._schema_on_200 is not None:
                return cls._schema_on_200

            cls._schema_on_200 = AAZObjectType()
            _UpdateHelper._build_schema_virtual_machine_run_command_read(cls._schema_on_200)

            return cls._schema_on_200

    class VirtualMachineRunCommandsCreateOrUpdate(AAZHttpOperation):
        CLIENT_TYPE = "MgmtClient"

        def __call__(self, *args, **kwargs):
            request = self.make_request()
            session = self.client.send_request(request=request, stream=False, **kwargs)
            if session.http_response.status_code in [202]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    path_format_arguments=self.url_parameters,
                )
            if session.http_response.status_code in [200, 201]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_201,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    path_format_arguments=self.url_parameters,
                )

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/runCommands/{runCommandName}",
                **self.url_parameters
            )

        @property
        def method(self):
            return "PUT"

        @property
        def error_format(self):
            return "ODataV4Format"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "runCommandName", self.ctx.args.run_command_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
                **self.serialize_url_param(
                    "vmName", self.ctx.args.vm_name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2024-11-01",
                    required=True,
                ),
            }
            return parameters

        @property
        def header_parameters(self):
            parameters = {
                **self.serialize_header_param(
                    "Content-Type", "application/json",
                ),
                **self.serialize_header_param(
                    "Accept", "application/json",
                ),
            }
            return parameters

        @property
        def content(self):
            _content_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

        def on_200_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_200_201
            )

        _schema_on_200_201 = None

        @classmethod
        def _build_schema_on_200_201(cls):
            if cls._schema_on_200_201 is not None:
                return cls._schema_on_200_201

            cls._schema_on_200_201 = AAZObjectType()
            _UpdateHelper._build_schema_virtual_machine_run_command_read(cls._schema_on_200_201)

            return cls._schema_on_200_201

    class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance(self.ctx.vars.instance)

        def _update_instance(self, instance):
            _instance_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=instance,
                typ=AAZObjectType
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("asyncExecution", AAZBoolType, ".async_execution")
                properties.set_prop("errorBlobUri", AAZStrType, ".error_blob_uri")
                properties.set_prop("outputBlobUri", AAZStrType, ".output_blob_uri")
                properties.set_prop("parameters", AAZListType, ".parameters")
                properties.set_prop("protectedParameters", AAZListType, ".protected_parameters")
                properties.set_prop("runAsPassword", AAZStrType, ".run_as_password")
                properties.set_prop("runAsUser", AAZStrType, ".run_as_user")
                properties.set_prop("source", AAZObjectType)
                properties.set_prop("timeoutInSeconds", AAZIntType, ".timeout_in_seconds")

            parameters = _builder.get(".properties.parameters")
            if parameters is not None:
                _UpdateHelper._build_schema_run_command_input_parameter_update(parameters.set_elements(AAZObjectType, "."))

            protected_parameters = _builder.get(".properties.protectedParameters")
            if protected_parameters is not None:
                _UpdateHelper._build_schema_run_command_input_parameter_update(protected_parameters.set_elements(AAZObjectType, "."))

            source = _builder.get(".properties.source")
            if source is not None:
                source.set_prop("commandId", AAZStrType, ".command_id")
                source.set_prop("script", AAZStrType, ".script")
                source.set_prop("scriptUri", AAZStrType, ".script_uri")

            tags = _builder.get(".tags")
            if tags is not None:
                tags.set_elements(AAZStrType, ".")

            return _instance_value

    class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance_by_generic(
                self.ctx.vars.instance,
                self.ctx.generic_update_args
            )


class _UpdateHelper:
    """Helper class for Update"""

    @classmethod
    def _build_schema_run_command_input_parameter_update(cls, _builder):
        if _builder is None:
            return
        _builder.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}})
        _builder.set_prop("value", AAZStrType, ".value", typ_kwargs={"flags": {"required": True}})

    @classmethod
    def _build_schema_run_command_managed_identity_update(cls, _builder):
        if _builder is None:
            return
        _builder.set_prop("clientId", AAZStrType, ".client_id")
        _builder.set_prop("objectId", AAZStrType, ".object_id")

    _schema_run_command_input_parameter_read = None

    @classmethod
    def _build_schema_run_command_input_parameter_read(cls, _schema):
        if cls._schema_run_command_input_parameter_read is not None:
            _schema.name = cls._schema_run_command_input_parameter_read.name
            _schema.value = cls._schema_run_command_input_parameter_read.value
            return

        cls._schema_run_command_input_parameter_read = _schema_run_command_input_parameter_read = AAZObjectType()

        run_command_input_parameter_read = _schema_run_command_input_parameter_read
        run_command_input_parameter_read.name = AAZStrType(
            flags={"required": True},
        )
        run_command_input_parameter_read.value = AAZStrType(
            flags={"required": True},
        )

        _schema.name = cls._schema_run_command_input_parameter_read.name
        _schema.value = cls._schema_run_command_input_parameter_read.value

    _schema_run_command_managed_identity_read = None

    @classmethod
    def _build_schema_run_command_managed_identity_read(cls, _schema):
        if cls._schema_run_command_managed_identity_read is not None:
            _schema.client_id = cls._schema_run_command_managed_identity_read.client_id
            _schema.object_id = cls._schema_run_command_managed_identity_read.object_id
            return

        cls._schema_run_command_managed_identity_read = _schema_run_command_managed_identity_read = AAZObjectType()

        run_command_managed_identity_read = _schema_run_command_managed_identity_read
        run_command_managed_identity_read.client_id = AAZStrType(
            serialized_name="clientId",
        )
        run_command_managed_identity_read.object_id = AAZStrType(
            serialized_name="objectId",
        )

        _schema.client_id = cls._schema_run_command_managed_identity_read.client_id
        _schema.object_id = cls._schema_run_command_managed_identity_read.object_id

    _schema_virtual_machine_run_command_read = None

    @classmethod
    def _build_schema_virtual_machine_run_command_read(cls, _schema):
        if cls._schema_virtual_machine_run_command_read is not None:
            _schema.id = cls._schema_virtual_machine_run_command_read.id
            _schema.location = cls._schema_virtual_machine_run_command_read.location
            _schema.name = cls._schema_virtual_machine_run_command_read.name
            _schema.properties = cls._schema_virtual_machine_run_command_read.properties
            _schema.system_data = cls._schema_virtual_machine_run_command_read.system_data
            _schema.tags = cls._schema_virtual_machine_run_command_read.tags
            _schema.type = cls._schema_virtual_machine_run_command_read.type
            return

        cls._schema_virtual_machine_run_command_read = _schema_virtual_machine_run_command_read = AAZObjectType()

        virtual_machine_run_command_read = _schema_virtual_machine_run_command_read
        virtual_machine_run_command_read.id = AAZStrType(
            flags={"read_only": True},
        )
        virtual_machine_run_command_read.location = AAZStrType(
            flags={"required": True},
        )
        virtual_machine_run_command_read.name = AAZStrType(
            flags={"read_only": True},
        )
        virtual_machine_run_command_read.properties = AAZObjectType(
            flags={"client_flatten": True},
        )
        virtual_machine_run_command_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        virtual_machine_run_command_read.tags = AAZDictType()
        virtual_machine_run_command_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_virtual_machine_run_command_read.properties
        properties.async_execution = AAZBoolType(
            serialized_name="asyncExecution",
        )
        properties.error_blob_managed_identity = AAZObjectType(
            serialized_name="errorBlobManagedIdentity",
        )
        cls._build_schema_run_command_managed_identity_read(properties.error_blob_managed_identity)
        properties.error_blob_uri = AAZStrType(
            serialized_name="errorBlobUri",
        )
        properties.instance_view = AAZObjectType(
            serialized_name="instanceView",
            flags={"read_only": True},
        )
        properties.output_blob_managed_identity = AAZObjectType(
            serialized_name="outputBlobManagedIdentity",
        )
        cls._build_schema_run_command_managed_identity_read(properties.output_blob_managed_identity)
        properties.output_blob_uri = AAZStrType(
            serialized_name="outputBlobUri",
        )
        properties.parameters = AAZListType()
        properties.protected_parameters = AAZListType(
            serialized_name="protectedParameters",
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.run_as_password = AAZStrType(
            serialized_name="runAsPassword",
        )
        properties.run_as_user = AAZStrType(
            serialized_name="runAsUser",
        )
        properties.source = AAZObjectType()
        properties.timeout_in_seconds = AAZIntType(
            serialized_name="timeoutInSeconds",
        )
        properties.treat_failure_as_deployment_failure = AAZBoolType(
            serialized_name="treatFailureAsDeploymentFailure",
        )

        instance_view = _schema_virtual_machine_run_command_read.properties.instance_view
        instance_view.end_time = AAZStrType(
            serialized_name="endTime",
        )
        instance_view.error = AAZStrType()
        instance_view.execution_message = AAZStrType(
            serialized_name="executionMessage",
        )
        instance_view.execution_state = AAZStrType(
            serialized_name="executionState",
        )
        instance_view.exit_code = AAZIntType(
            serialized_name="exitCode",
        )
        instance_view.output = AAZStrType()
        instance_view.start_time = AAZStrType(
            serialized_name="startTime",
        )
        instance_view.statuses = AAZListType()

        statuses = _schema_virtual_machine_run_command_read.properties.instance_view.statuses
        statuses.Element = AAZObjectType()

        _element = _schema_virtual_machine_run_command_read.properties.instance_view.statuses.Element
        _element.code = AAZStrType()
        _element.display_status = AAZStrType(
            serialized_name="displayStatus",
        )
        _element.level = AAZStrType()
        _element.message = AAZStrType()
        _element.time = AAZStrType()

        parameters = _schema_virtual_machine_run_command_read.properties.parameters
        parameters.Element = AAZObjectType()
        cls._build_schema_run_command_input_parameter_read(parameters.Element)

        protected_parameters = _schema_virtual_machine_run_command_read.properties.protected_parameters
        protected_parameters.Element = AAZObjectType()
        cls._build_schema_run_command_input_parameter_read(protected_parameters.Element)

        source = _schema_virtual_machine_run_command_read.properties.source
        source.command_id = AAZStrType(
            serialized_name="commandId",
        )
        source.script = AAZStrType()
        source.script_uri = AAZStrType(
            serialized_name="scriptUri",
        )
        source.script_uri_managed_identity = AAZObjectType(
            serialized_name="scriptUriManagedIdentity",
        )
        cls._build_schema_run_command_managed_identity_read(source.script_uri_managed_identity)

        system_data = _schema_virtual_machine_run_command_read.system_data
        system_data.created_at = AAZStrType(
            serialized_name="createdAt",
        )
        system_data.created_by = AAZStrType(
            serialized_name="createdBy",
        )
        system_data.created_by_type = AAZStrType(
            serialized_name="createdByType",
        )
        system_data.last_modified_at = AAZStrType(
            serialized_name="lastModifiedAt",
        )
        system_data.last_modified_by = AAZStrType(
            serialized_name="lastModifiedBy",
        )
        system_data.last_modified_by_type = AAZStrType(
            serialized_name="lastModifiedByType",
        )

        tags = _schema_virtual_machine_run_command_read.tags
        tags.Element = AAZStrType()

        _schema.id = cls._schema_virtual_machine_run_command_read.id
        _schema.location = cls._schema_virtual_machine_run_command_read.location
        _schema.name = cls._schema_virtual_machine_run_command_read.name
        _schema.properties = cls._schema_virtual_machine_run_command_read.properties
        _schema.system_data = cls._schema_virtual_machine_run_command_read.system_data
        _schema.tags = cls._schema_virtual_machine_run_command_read.tags
        _schema.type = cls._schema_virtual_machine_run_command_read.type


__all__ = ["Update"]
