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

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

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

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

    _aaz_info = {
        "version": "2026-01-01-preview",
        "resources": [
            ["mgmt-plane", "/{scope}/providers/microsoft.authorization/policyenrollments/{}", "2026-01-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 enrollment.",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[^<>%&:\\?/]*[^<>%&:\\?/ ]+$",
            ),
        )
        _args_schema.scope = AAZStrArg(
            options=["--scope"],
            help="The fully qualified Azure Resource manager identifier of the resource.",
            required=True,
        )

        # define Arg Group "Parameters"

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.assignment_scope_validation = AAZStrArg(
            options=["-v", "--assignment-scope-validation"],
            arg_group="Properties",
            help="The option whether to validate the enrollment is at or under the assignment scope.",
            nullable=True,
            enum={"Default": "Default", "DoNotValidate": "DoNotValidate"},
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help="The description of the policy enrollment.",
            nullable=True,
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help="The display name of the policy enrollment.",
            nullable=True,
        )
        _args_schema.metadata = AAZAnyTypeArg(
            options=["--metadata"],
            arg_group="Properties",
            help="The policy enrollment metadata. Metadata is an open ended object and is typically a collection of key value pairs.",
            nullable=True,
        )
        _args_schema.policy_assignment = AAZResourceIdArg(
            options=["-a", "--policy-assignment"],
            arg_group="Properties",
            help={"short-summary": "The policy assignment to enroll.", "long-summary": "The resource ID of the policy assignment to enroll."},
        )
        _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 enroll 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="The resource selector list to filter policies by resource properties.",
            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={"groupPrincipalId": "groupPrincipalId", "policyDefinitionReferenceId": "policyDefinitionReferenceId", "resourceLocation": "resourceLocation", "resourceType": "resourceType", "resourceWithoutLocation": "resourceWithoutLocation", "userPrincipalId": "userPrincipalId"},
        )
        _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.PolicyEnrollmentsGet(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.PolicyEnrollmentsCreateOrUpdate(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 PolicyEnrollmentsGet(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/policyEnrollments/{policyEnrollmentName}",
                **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(
                    "policyEnrollmentName", 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", "2026-01-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_enrollment_read(cls._schema_on_200)

            return cls._schema_on_200

    class PolicyEnrollmentsCreateOrUpdate(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/policyEnrollments/{policyEnrollmentName}",
                **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(
                    "policyEnrollmentName", 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", "2026-01-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_enrollment_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}})

            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("metadata", AAZAnyType, ".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")

            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_enrollment_read = None

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

        cls._schema_policy_enrollment_read = _schema_policy_enrollment_read = AAZObjectType()

        policy_enrollment_read = _schema_policy_enrollment_read
        policy_enrollment_read.e_tag = AAZStrType(
            serialized_name="eTag",
        )
        policy_enrollment_read.id = AAZStrType(
            flags={"read_only": True},
        )
        policy_enrollment_read.name = AAZStrType(
            flags={"read_only": True},
        )
        policy_enrollment_read.properties = AAZObjectType(
            flags={"client_flatten": True},
        )
        policy_enrollment_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        policy_enrollment_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_policy_enrollment_read.properties
        properties.assignment_scope_validation = AAZStrType(
            serialized_name="assignmentScopeValidation",
        )
        properties.description = AAZStrType()
        properties.display_name = AAZStrType(
            serialized_name="displayName",
        )
        properties.metadata = AAZAnyType()
        properties.policy_assignment_id = AAZStrType(
            serialized_name="policyAssignmentId",
            flags={"required": True},
        )
        properties.policy_assignment_instance_id = AAZStrType(
            serialized_name="policyAssignmentInstanceId",
            flags={"read_only": True},
        )
        properties.policy_definition_reference_ids = AAZListType(
            serialized_name="policyDefinitionReferenceIds",
        )
        properties.resource_selectors = AAZListType(
            serialized_name="resourceSelectors",
        )

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

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

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

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

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

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

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

        system_data = _schema_policy_enrollment_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.e_tag = cls._schema_policy_enrollment_read.e_tag
        _schema.id = cls._schema_policy_enrollment_read.id
        _schema.name = cls._schema_policy_enrollment_read.name
        _schema.properties = cls._schema_policy_enrollment_read.properties
        _schema.system_data = cls._schema_policy_enrollment_read.system_data
        _schema.type = cls._schema_policy_enrollment_read.type


__all__ = ["Update"]
