# --------------------------------------------------------------------------------------------
# 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(
    "policy exemption update",
)
class Update(AAZCommand):
    """Update a policy exemption.

    Update the policy exemption with the given name and scope by applying the given property values.

    :example: Update a policy exemption category
        az policy exemption update -n exemptTestVM --exemption-category "Mitigated"

    :example: Update a policy exemption in a resource group
        az policy exemption update -n exemptTestVM --display-name "Updated display name" --resource-group myResourceGroup

    :example: Update a policy exemption at scope
        az policy exemption update -n exemptTestVM --description "This exemption is very cool." --scope "/providers/Microsoft.Management/managementGroups/{managementGroupName}"
    """

    _aaz_info = {
        "version": "2022-07-01-preview",
        "resources": [
            ["mgmt-plane", "/{scope}/providers/microsoft.authorization/policyexemptions/{}", "2022-07-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="The name of the policy exemption.",
            required=True,
        )
        _args_schema.scope = AAZStrArg(
            options=["--scope"],
            help={"short-summary": "The scope of the policy assignment.", "long-summary": "Valid scopes are: management group (format: '/providers/Microsoft.Management/managementGroups/{managementGroup}'), subscription (format: '/subscriptions/{subscriptionId}'), resource group (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}', or resource (format: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/[{parentResourcePath}/]{resourceType}/{resourceName}'. The scope of an assignment is always the part of its ID preceding '/providers/Microsoft.Authorization/policyAssignments/{policyAssignmentName}'. If scope is not provided, the scope will be the implied or specified subscription."},
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.assignment_scope_validation = AAZStrArg(
            options=["-v", "--assignment-scope-validation"],
            arg_group="Properties",
            help={"short-summary": "The assignment scope validation", "long-summary": "Indicates the type of validation to perform on the assignment scope. Valid values are Default, DoNotValidate."},
            nullable=True,
            enum={"Default": "Default", "DoNotValidate": "DoNotValidate"},
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help={"short-summary": "Policy exemption description.", "long-summary": "Full description of the policy exemption."},
            nullable=True,
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help={"short-summary": "The display name of the policy exemption.", "long-summary": "The display name of the policy exemption is not part of its ID, allowing for longer and more flexible naming."},
            nullable=True,
        )
        _args_schema.exemption_category = AAZStrArg(
            options=["-e", "--exemption-category"],
            arg_group="Properties",
            help={"short-summary": "The policy exemption category.", "long-summary": "The policy exemption category. Possible values are Mitigated and Waiver."},
            enum={"Mitigated": "Mitigated", "Waiver": "Waiver"},
        )
        _args_schema.expires_on = AAZDateTimeArg(
            options=["--expires-on"],
            arg_group="Properties",
            help={"short-summary": "The expiration date and time.", "long-summary": "The expiration date and time of the policy exemption in UTC ISO 8601 format, e.g. yyyy-MM-ddTHH:mm:ssZ."},
            nullable=True,
        )
        _args_schema.metadata = AAZDictArg(
            options=["--metadata"],
            arg_group="Properties",
            help={"short-summary": "The policy exemption metadata.", "long-summary": "The policy exemption metadata. Metadata is an open-ended object and is typically a collection of key value pairs."},
            nullable=True,
        )
        _args_schema.policy_assignment = AAZStrArg(
            options=["-a", "--policy-assignment"],
            arg_group="Properties",
            help={"short-summary": "The policy assignment to exempt.", "long-summary": "The resource ID of the policy assignment to exempt."},
        )
        _args_schema.policy_definition_reference_ids = AAZListArg(
            options=["-r", "--policy-definition-reference-ids"],
            arg_group="Properties",
            help={"short-summary": "The policy definition reference IDs.", "long-summary": "The collection of policy definition reference IDs to exempt when the policy assignment is an assignment of a policy set definition."},
            nullable=True,
        )
        _args_schema.resource_selectors = AAZListArg(
            options=["--resource-selectors"],
            arg_group="Properties",
            help={"short-summary": "The resource selectors list to filter policies by resource properties.", "long-summary": "The collection of resource selector expressions used to filter policy exemption applicability by certain resource property values."},
            nullable=True,
        )

        metadata = cls._args_schema.metadata
        metadata.Element = AAZAnyTypeArg(
            nullable=True,
        )

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

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

        _element = cls._args_schema.resource_selectors.Element
        _element.name = AAZStrArg(
            options=["name"],
            help="The name of the resource selector.",
            nullable=True,
        )
        _element.selectors = AAZListArg(
            options=["selectors"],
            help="The list of the selector expressions.",
            nullable=True,
        )

        selectors = cls._args_schema.resource_selectors.Element.selectors
        selectors.Element = AAZObjectArg(
            nullable=True,
        )

        _element = cls._args_schema.resource_selectors.Element.selectors.Element
        _element.in_ = AAZListArg(
            options=["in"],
            help="The list of values to filter in.",
            nullable=True,
        )
        _element.kind = AAZStrArg(
            options=["kind"],
            help="The selector kind.",
            nullable=True,
            enum={"policyDefinitionReferenceId": "policyDefinitionReferenceId", "resourceLocation": "resourceLocation", "resourceType": "resourceType", "resourceWithoutLocation": "resourceWithoutLocation"},
        )
        _element.not_in = AAZListArg(
            options=["not-in"],
            help="The list of values to filter out.",
            nullable=True,
        )

        in_ = cls._args_schema.resource_selectors.Element.selectors.Element.in_
        in_.Element = AAZStrArg(
            nullable=True,
        )

        not_in = cls._args_schema.resource_selectors.Element.selectors.Element.not_in
        not_in.Element = AAZStrArg(
            nullable=True,
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.PolicyExemptionsGet(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.PolicyExemptionsCreateOrUpdate(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 PolicyExemptionsGet(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(
                "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}",
                **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(
                    "policyExemptionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "scope", self.ctx.args.scope,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2022-07-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_policy_exemption_read(cls._schema_on_200)

            return cls._schema_on_200

    class PolicyExemptionsCreateOrUpdate(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, 201]:
                return self.on_200_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/{scope}/providers/Microsoft.Authorization/policyExemptions/{policyExemptionName}",
                **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(
                    "policyExemptionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "scope", self.ctx.args.scope,
                    skip_quote=True,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2022-07-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_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_policy_exemption_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": {"required": True, "client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("assignmentScopeValidation", AAZStrType, ".assignment_scope_validation")
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("displayName", AAZStrType, ".display_name")
                properties.set_prop("exemptionCategory", AAZStrType, ".exemption_category", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("expiresOn", AAZStrType, ".expires_on")
                properties.set_prop("metadata", AAZDictType, ".metadata")
                properties.set_prop("policyAssignmentId", AAZStrType, ".policy_assignment", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("policyDefinitionReferenceIds", AAZListType, ".policy_definition_reference_ids")
                properties.set_prop("resourceSelectors", AAZListType, ".resource_selectors")

            metadata = _builder.get(".properties.metadata")
            if metadata is not None:
                metadata.set_elements(AAZAnyType, ".")

            policy_definition_reference_ids = _builder.get(".properties.policyDefinitionReferenceIds")
            if policy_definition_reference_ids is not None:
                policy_definition_reference_ids.set_elements(AAZStrType, ".")

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

            _elements = _builder.get(".properties.resourceSelectors[]")
            if _elements is not None:
                _elements.set_prop("name", AAZStrType, ".name")
                _elements.set_prop("selectors", AAZListType, ".selectors")

            selectors = _builder.get(".properties.resourceSelectors[].selectors")
            if selectors is not None:
                selectors.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.resourceSelectors[].selectors[]")
            if _elements is not None:
                _elements.set_prop("in", AAZListType, ".in_")
                _elements.set_prop("kind", AAZStrType, ".kind")
                _elements.set_prop("notIn", AAZListType, ".not_in")

            in_ = _builder.get(".properties.resourceSelectors[].selectors[].in")
            if in_ is not None:
                in_.set_elements(AAZStrType, ".")

            not_in = _builder.get(".properties.resourceSelectors[].selectors[].notIn")
            if not_in is not None:
                not_in.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_policy_exemption_read = None

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

        cls._schema_policy_exemption_read = _schema_policy_exemption_read = AAZObjectType()

        policy_exemption_read = _schema_policy_exemption_read
        policy_exemption_read.id = AAZStrType(
            flags={"read_only": True},
        )
        policy_exemption_read.name = AAZStrType(
            flags={"read_only": True},
        )
        policy_exemption_read.properties = AAZObjectType(
            flags={"required": True, "client_flatten": True},
        )
        policy_exemption_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        policy_exemption_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_policy_exemption_read.properties
        properties.assignment_scope_validation = AAZStrType(
            serialized_name="assignmentScopeValidation",
        )
        properties.description = AAZStrType()
        properties.display_name = AAZStrType(
            serialized_name="displayName",
        )
        properties.exemption_category = AAZStrType(
            serialized_name="exemptionCategory",
            flags={"required": True},
        )
        properties.expires_on = AAZStrType(
            serialized_name="expiresOn",
        )
        properties.metadata = AAZDictType()
        properties.policy_assignment_id = AAZStrType(
            serialized_name="policyAssignmentId",
            flags={"required": True},
        )
        properties.policy_definition_reference_ids = AAZListType(
            serialized_name="policyDefinitionReferenceIds",
        )
        properties.resource_selectors = AAZListType(
            serialized_name="resourceSelectors",
        )

        metadata = _schema_policy_exemption_read.properties.metadata
        metadata.Element = AAZAnyType()

        policy_definition_reference_ids = _schema_policy_exemption_read.properties.policy_definition_reference_ids
        policy_definition_reference_ids.Element = AAZStrType()

        resource_selectors = _schema_policy_exemption_read.properties.resource_selectors
        resource_selectors.Element = AAZObjectType()

        _element = _schema_policy_exemption_read.properties.resource_selectors.Element
        _element.name = AAZStrType()
        _element.selectors = AAZListType()

        selectors = _schema_policy_exemption_read.properties.resource_selectors.Element.selectors
        selectors.Element = AAZObjectType()

        _element = _schema_policy_exemption_read.properties.resource_selectors.Element.selectors.Element
        _element["in"] = AAZListType()
        _element.kind = AAZStrType()
        _element.not_in = AAZListType(
            serialized_name="notIn",
        )

        in_ = _schema_policy_exemption_read.properties.resource_selectors.Element.selectors.Element["in"]
        in_.Element = AAZStrType()

        not_in = _schema_policy_exemption_read.properties.resource_selectors.Element.selectors.Element.not_in
        not_in.Element = AAZStrType()

        system_data = _schema_policy_exemption_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",
        )

        _schema.id = cls._schema_policy_exemption_read.id
        _schema.name = cls._schema_policy_exemption_read.name
        _schema.properties = cls._schema_policy_exemption_read.properties
        _schema.system_data = cls._schema_policy_exemption_read.system_data
        _schema.type = cls._schema_policy_exemption_read.type


__all__ = ["Update"]
