# --------------------------------------------------------------------------------------------
# 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 *


@register_command(
    "blueprint update",
    is_preview=True,
)
class Update(AAZCommand):
    """Update a blueprint definition.
    """

    _aaz_info = {
        "version": "2018-11-01-preview",
        "resources": [
            ["mgmt-plane", "/{resourcescope}/providers/microsoft.blueprint/blueprints/{}", "2018-11-01-preview"],
        ]
    }

    AZ_SUPPORT_GENERIC_UPDATE = True

    def _handler(self, command_args):
        super()._handler(command_args)
        self._execute_operations()
        return 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.name = AAZStrArg(
            options=["-n", "--name"],
            help="Name of the blueprint definition.",
            required=True,
        )
        _args_schema.resource_scope = AAZStrArg(
            options=["--resource-scope"],
            help="The scope of the resource. Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}').",
            required=True,
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            help="Multi-line explain this resource.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=500,
            ),
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            help="One-liner string explain this resource.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=256,
            ),
        )
        _args_schema.parameters = AAZDictArg(
            options=["-p", "--parameters"],
            help="Parameters required by this blueprint definition. It can be a JSON                             string or JSON file path.",
            nullable=True,
        )
        _args_schema.resource_groups = AAZDictArg(
            options=["--resource-groups"],
            help="Resource group placeholders defined by this blueprint definition.",
            nullable=True,
        )
        _args_schema.target_scope = AAZStrArg(
            options=["--target-scope"],
            help="The scope where this blueprint definition can be assigned.",
            enum={"managementGroup": "managementGroup", "subscription": "subscription"},
        )

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

        _element = cls._args_schema.parameters.Element
        _element.allowed_values = AAZListArg(
            options=["allowed-values"],
            help="Array of allowed values for this parameter.",
            nullable=True,
        )
        _element.default_value = AAZStrArg(
            options=["default-value"],
            help="Default Value for this parameter.",
            nullable=True,
        )
        _element.description = AAZStrArg(
            options=["description"],
            help="Description of this parameter/resourceGroup.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=500,
            ),
        )
        _element.display_name = AAZStrArg(
            options=["display-name"],
            help="DisplayName of this parameter/resourceGroup.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=256,
            ),
        )
        _element.strong_type = AAZStrArg(
            options=["strong-type"],
            help="StrongType for UI to render rich experience during blueprint assignment. Supported strong types are resourceType, principalId and location.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=64,
            ),
        )
        _element.type = AAZStrArg(
            options=["type"],
            help="Allowed data types for Resource Manager template parameters.",
            enum={"array": "array", "bool": "bool", "int": "int", "object": "object", "secureObject": "secureObject", "secureString": "secureString", "string": "string"},
        )

        allowed_values = cls._args_schema.parameters.Element.allowed_values
        allowed_values.Element = AAZStrArg(
            nullable=True,
        )

        resource_groups = cls._args_schema.resource_groups
        resource_groups.Element = AAZObjectArg(
            nullable=True,
        )

        _element = cls._args_schema.resource_groups.Element
        _element.depends_on = AAZListArg(
            options=["depends-on"],
            help="Artifacts which need to be deployed before this resource group.",
            nullable=True,
        )
        _element.location = AAZStrArg(
            options=["location"],
            help="Location of this resourceGroup. Leave empty if the resource group location will be specified during the blueprint assignment.",
            nullable=True,
        )
        _element.description = AAZStrArg(
            options=["description"],
            help="Description of this parameter/resourceGroup.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=500,
            ),
        )
        _element.display_name = AAZStrArg(
            options=["display-name"],
            help="DisplayName of this parameter/resourceGroup.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=256,
            ),
        )
        _element.strong_type = AAZStrArg(
            options=["strong-type"],
            help="StrongType for UI to render rich experience during blueprint assignment. Supported strong types are resourceType, principalId and location.",
            nullable=True,
            fmt=AAZStrArgFormat(
                max_length=64,
            ),
        )
        _element.name = AAZStrArg(
            options=["name"],
            help="Name of this resourceGroup. Leave empty if the resource group name will be specified during the blueprint assignment.",
            nullable=True,
        )
        _element.tags = AAZDictArg(
            options=["tags"],
            help="Tags to be assigned to this resource group.",
            nullable=True,
        )

        depends_on = cls._args_schema.resource_groups.Element.depends_on
        depends_on.Element = AAZStrArg(
            nullable=True,
        )

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

    def _execute_operations(self):
        self.pre_operations()
        self.BlueprintsGet(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)
        self.BlueprintsCreateOrUpdate(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 BlueprintsGet(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(
                "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "blueprintName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceScope", self.ctx.args.resource_scope,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2018-11-01-preview",
                    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_blueprint_read(cls._schema_on_200)

            return cls._schema_on_200

    class BlueprintsCreateOrUpdate(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 [201]:
                return self.on_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/{resourceScope}/providers/Microsoft.Blueprint/blueprints/{blueprintName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "blueprintName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceScope", self.ctx.args.resource_scope,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2018-11-01-preview",
                    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_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_201
            )

        _schema_on_201 = None

        @classmethod
        def _build_schema_on_201(cls):
            if cls._schema_on_201 is not None:
                return cls._schema_on_201

            cls._schema_on_201 = AAZObjectType()
            _UpdateHelper._build_schema_blueprint_read(cls._schema_on_201)

            return cls._schema_on_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": {"required": True, "client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("displayName", AAZStrType, ".display_name")
                properties.set_prop("parameters", AAZDictType, ".parameters")
                properties.set_prop("resourceGroups", AAZDictType, ".resource_groups")
                properties.set_prop("targetScope", AAZStrType, ".target_scope", typ_kwargs={"flags": {"required": True}})

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

            _elements = _builder.get(".properties.parameters{}")
            if _elements is not None:
                _elements.set_prop("allowedValues", AAZListType, ".allowed_values")
                _elements.set_prop("defaultValue", AAZStrType, ".default_value")
                _elements.set_prop("metadata", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})
                _elements.set_prop("type", AAZStrType, ".type", typ_kwargs={"flags": {"required": True}})

            allowed_values = _builder.get(".properties.parameters{}.allowedValues")
            if allowed_values is not None:
                allowed_values.set_elements(AAZStrType, ".")

            metadata = _builder.get(".properties.parameters{}.metadata")
            if metadata is not None:
                metadata.set_prop("description", AAZStrType, ".description")
                metadata.set_prop("displayName", AAZStrType, ".display_name")
                metadata.set_prop("strongType", AAZStrType, ".strong_type")

            resource_groups = _builder.get(".properties.resourceGroups")
            if resource_groups is not None:
                resource_groups.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.resourceGroups{}")
            if _elements is not None:
                _elements.set_prop("dependsOn", AAZListType, ".depends_on")
                _elements.set_prop("location", AAZStrType, ".location")
                _elements.set_prop("metadata", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})
                _elements.set_prop("name", AAZStrType, ".name")
                _elements.set_prop("tags", AAZDictType, ".tags")

            depends_on = _builder.get(".properties.resourceGroups{}.dependsOn")
            if depends_on is not None:
                depends_on.set_elements(AAZStrType, ".")

            metadata = _builder.get(".properties.resourceGroups{}.metadata")
            if metadata is not None:
                metadata.set_prop("description", AAZStrType, ".description")
                metadata.set_prop("displayName", AAZStrType, ".display_name")
                metadata.set_prop("strongType", AAZStrType, ".strong_type")

            tags = _builder.get(".properties.resourceGroups{}.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"""

    _schema_blueprint_read = None

    @classmethod
    def _build_schema_blueprint_read(cls, _schema):
        if cls._schema_blueprint_read is not None:
            _schema.id = cls._schema_blueprint_read.id
            _schema.name = cls._schema_blueprint_read.name
            _schema.properties = cls._schema_blueprint_read.properties
            _schema.type = cls._schema_blueprint_read.type
            return

        cls._schema_blueprint_read = _schema_blueprint_read = AAZObjectType()

        blueprint_read = _schema_blueprint_read
        blueprint_read.id = AAZStrType(
            flags={"read_only": True},
        )
        blueprint_read.name = AAZStrType(
            flags={"read_only": True},
        )
        blueprint_read.properties = AAZObjectType(
            flags={"required": True, "client_flatten": True},
        )
        blueprint_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_blueprint_read.properties
        properties.description = AAZStrType()
        properties.display_name = AAZStrType(
            serialized_name="displayName",
        )
        properties.parameters = AAZDictType()
        properties.resource_groups = AAZDictType(
            serialized_name="resourceGroups",
        )
        properties.status = AAZObjectType()
        properties.target_scope = AAZStrType(
            serialized_name="targetScope",
            flags={"required": True},
        )

        parameters = _schema_blueprint_read.properties.parameters
        parameters.Element = AAZObjectType()

        _element = _schema_blueprint_read.properties.parameters.Element
        _element.allowed_values = AAZListType(
            serialized_name="allowedValues",
        )
        _element.default_value = AAZStrType(
            serialized_name="defaultValue",
        )
        _element.metadata = AAZObjectType(
            flags={"client_flatten": True},
        )
        cls._build_schema_parameter_definition_metadata_read(_element.metadata)
        _element.type = AAZStrType(
            flags={"required": True},
        )

        allowed_values = _schema_blueprint_read.properties.parameters.Element.allowed_values
        allowed_values.Element = AAZStrType()

        resource_groups = _schema_blueprint_read.properties.resource_groups
        resource_groups.Element = AAZObjectType()

        _element = _schema_blueprint_read.properties.resource_groups.Element
        _element.depends_on = AAZListType(
            serialized_name="dependsOn",
        )
        _element.location = AAZStrType()
        _element.metadata = AAZObjectType(
            flags={"client_flatten": True},
        )
        cls._build_schema_parameter_definition_metadata_read(_element.metadata)
        _element.name = AAZStrType()
        _element.tags = AAZDictType()

        depends_on = _schema_blueprint_read.properties.resource_groups.Element.depends_on
        depends_on.Element = AAZStrType()

        tags = _schema_blueprint_read.properties.resource_groups.Element.tags
        tags.Element = AAZStrType()

        status = _schema_blueprint_read.properties.status
        status.last_modified = AAZStrType(
            serialized_name="lastModified",
            flags={"read_only": True},
        )
        status.time_created = AAZStrType(
            serialized_name="timeCreated",
            flags={"read_only": True},
        )

        _schema.id = cls._schema_blueprint_read.id
        _schema.name = cls._schema_blueprint_read.name
        _schema.properties = cls._schema_blueprint_read.properties
        _schema.type = cls._schema_blueprint_read.type

    _schema_parameter_definition_metadata_read = None

    @classmethod
    def _build_schema_parameter_definition_metadata_read(cls, _schema):
        if cls._schema_parameter_definition_metadata_read is not None:
            _schema.description = cls._schema_parameter_definition_metadata_read.description
            _schema.display_name = cls._schema_parameter_definition_metadata_read.display_name
            _schema.strong_type = cls._schema_parameter_definition_metadata_read.strong_type
            return

        cls._schema_parameter_definition_metadata_read = _schema_parameter_definition_metadata_read = AAZObjectType()

        parameter_definition_metadata_read = _schema_parameter_definition_metadata_read
        parameter_definition_metadata_read.description = AAZStrType()
        parameter_definition_metadata_read.display_name = AAZStrType(
            serialized_name="displayName",
        )
        parameter_definition_metadata_read.strong_type = AAZStrType(
            serialized_name="strongType",
        )

        _schema.description = cls._schema_parameter_definition_metadata_read.description
        _schema.display_name = cls._schema_parameter_definition_metadata_read.display_name
        _schema.strong_type = cls._schema_parameter_definition_metadata_read.strong_type


__all__ = ["Update"]
