# --------------------------------------------------------------------------------------------
# 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 definition create",
)
class Create(AAZCommand):
    """Create a policy definition.

    Create a policy definition in the given subscription or management group with the given name and other properties.

    :example: Create a read-only storage policy
        az policy definition create --name readOnlyStorage --rules "{ 'if': { 'field': 'type', 'equals': 'Microsoft.Storage/storageAccounts/write' }, 'then': { 'effect': 'deny' } }"

    :example: Create a policy definition with parameters
        az policy definition create --name allowedLocations --rules "{ 'if': { 'allOf': [{ 'field': 'location','notIn': '[parameters(\\'listOfAllowedLocations\\')]' }, { 'field': 'location', 'notEquals': 'global' }, { 'field': 'type', 'notEquals': 'Microsoft.AzureActiveDirectory/b2cDirectories'}] }, 'then': { 'effect': 'deny' } }" --params "{ 'allowedLocations': {'type': 'array', 'metadata': { 'description': 'The list of locations that can be specified when deploying resources', 'strongType': 'location', 'displayName': 'Allowed locations' } } }"

    :example: Create a read-only storage policy that can be applied within a management group
        az policy definition create -n readOnlyStorage --management-group "MyManagementGroup" --rules "{ 'if': { 'field': 'type', 'equals': 'Microsoft.Storage/storageAccounts/write' }, 'then': { 'effect': 'deny' } }"

    :example: Create a policy definition with mode
        az policy definition create --name TagsPolicyDefinition --subscription "MySubscription" --mode Indexed --rules "{ 'if': { 'field': 'tags', 'exists': 'false' }, 'then': { 'effect': 'deny' } }"
    """

    _aaz_info = {
        "version": "2024-05-01",
        "resources": [
            ["mgmt-plane", "/providers/microsoft.management/managementgroups/{}/providers/microsoft.authorization/policydefinitions/{}", "2024-05-01"],
            ["mgmt-plane", "/subscriptions/{}/providers/microsoft.authorization/policydefinitions/{}", "2024-05-01"],
        ]
    }

    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.management_group = AAZStrArg(
            options=["--management-group"],
            help={"short-summary": "The management group.", "long-summary": "The management group with the given name is where the policy definition will reside. It can be assigned only at scopes at or below this management group."},
        )
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="The name of the policy definition.",
            required=True,
            fmt=AAZStrArgFormat(
                pattern="^[^<>*%&:\\?.+/]*[^<>*%&:\\?.+/ ]+$",
            ),
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help={"short-summary": "Policy definition description.", "long-summary": "Full description of the policy definition."},
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help={"short-summary": "The display name of the policy definition.", "long-summary": "The display name of the policy definition is not part of its ID, allowing for longer and more flexible naming."},
        )
        _args_schema.metadata = AAZDictArg(
            options=["--metadata"],
            arg_group="Properties",
            help={"short-summary": "The policy definition metadata.", "long-summary": "The policy definition metadata. Metadata is an open-ended object and is typically a collection of key value pairs."},
        )
        _args_schema.mode = AAZStrArg(
            options=["-m", "--mode"],
            arg_group="Properties",
            help={"short-summary": "The policy definition mode.", "long-summary": "The policy definition mode. Valid values for control plane policy definitions: All, Indexed. The mode 'Indexed' indicates the policy should be evaluated only for resource types that support tags and location. Some examples for data plane policy definitions: Microsoft.KeyVault.Data, Microsoft.Network.Data."},
            default="Indexed",
        )
        _args_schema.params = AAZDictArg(
            options=["-p", "--params"],
            arg_group="Properties",
            help={"short-summary": "The policy rule parameter definitions.", "long-summary": "The definitions for parameters used in the policy rule. The keys are the parameter names."},
        )
        _args_schema.rules = AAZDictArg(
            options=["--rule", "--rules"],
            arg_group="Properties",
            help="The policy rule.",
        )
        _args_schema.version = AAZStrArg(
            options=["--version"],
            arg_group="Properties",
            help={"short-summary": "The policy definition version.", "long-summary": "The policy definition version in #.#.# format."},
        )

        metadata = cls._args_schema.metadata
        metadata.Element = AAZAnyTypeArg()

        params = cls._args_schema.params
        params.Element = AAZObjectArg()

        _element = cls._args_schema.params.Element
        _element.allowed_values = AAZListArg(
            options=["allowed-values"],
            help="The allowed values for the parameter.",
        )
        _element.default_value = AAZAnyTypeArg(
            options=["default-value"],
            help="The default value for the parameter if no value is provided.",
        )
        _element.metadata = AAZFreeFormDictArg(
            options=["metadata"],
            help="General metadata for the parameter.",
        )
        _element.schema = AAZDictArg(
            options=["schema"],
            help="Provides validation of parameter inputs during assignment using a self-defined JSON schema. This property is only supported for object-type parameters and follows the Json.NET Schema 2019-09 implementation. You can learn more about using schemas at https://json-schema.org/ and test draft schemas at https://www.jsonschemavalidator.net/.",
        )
        _element.type = AAZStrArg(
            options=["type"],
            help="The data type of the parameter.",
            enum={"Array": "Array", "Boolean": "Boolean", "DateTime": "DateTime", "Float": "Float", "Integer": "Integer", "Object": "Object", "String": "String"},
        )

        allowed_values = cls._args_schema.params.Element.allowed_values
        allowed_values.Element = AAZAnyTypeArg()

        schema = cls._args_schema.params.Element.schema
        schema.Element = AAZAnyTypeArg()

        rules = cls._args_schema.rules
        rules.Element = AAZAnyTypeArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        condition_0 = has_value(self.ctx.args.management_group) and has_value(self.ctx.args.name)
        condition_1 = has_value(self.ctx.args.name) and has_value(self.ctx.subscription_id)
        if condition_0:
            self.PolicyDefinitionsCreateOrUpdateAtManagementGroup(ctx=self.ctx)()
        if condition_1:
            self.PolicyDefinitionsCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

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

    class PolicyDefinitionsCreateOrUpdateAtManagementGroup(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(
                "/providers/Microsoft.Management/managementGroups/{managementGroupId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **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(
                    "managementGroupId", self.ctx.args.management_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2024-05-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,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"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("metadata", AAZDictType, ".metadata")
                properties.set_prop("mode", AAZStrType, ".mode")
                properties.set_prop("parameters", AAZDictType, ".params")
                properties.set_prop("policyRule", AAZDictType, ".rules")
                properties.set_prop("version", AAZStrType, ".version")

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

            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", AAZAnyType, ".default_value")
                _elements.set_prop("metadata", AAZFreeFormDictType, ".metadata")
                _elements.set_prop("schema", AAZDictType, ".schema")
                _elements.set_prop("type", AAZStrType, ".type")

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

            metadata = _builder.get(".properties.parameters{}.metadata")
            if metadata is not None:
                metadata.set_anytype_elements(".")

            schema = _builder.get(".properties.parameters{}.schema")
            if schema is not None:
                schema.set_elements(AAZAnyType, ".")

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

            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()

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

            properties = cls._schema_on_201.properties
            properties.description = AAZStrType()
            properties.display_name = AAZStrType(
                serialized_name="displayName",
            )
            properties.metadata = AAZDictType()
            properties.mode = AAZStrType()
            properties.parameters = AAZDictType()
            properties.policy_rule = AAZDictType(
                serialized_name="policyRule",
            )
            properties.policy_type = AAZStrType(
                serialized_name="policyType",
            )
            properties.version = AAZStrType()
            properties.versions = AAZListType()

            metadata = cls._schema_on_201.properties.metadata
            metadata.Element = AAZAnyType()

            parameters = cls._schema_on_201.properties.parameters
            parameters.Element = AAZObjectType()

            _element = cls._schema_on_201.properties.parameters.Element
            _element.allowed_values = AAZListType(
                serialized_name="allowedValues",
            )
            _element.default_value = AAZAnyType(
                serialized_name="defaultValue",
            )
            _element.metadata = AAZFreeFormDictType()
            _element.schema = AAZDictType()
            _element.type = AAZStrType()

            allowed_values = cls._schema_on_201.properties.parameters.Element.allowed_values
            allowed_values.Element = AAZAnyType()

            schema = cls._schema_on_201.properties.parameters.Element.schema
            schema.Element = AAZAnyType()

            policy_rule = cls._schema_on_201.properties.policy_rule
            policy_rule.Element = AAZAnyType()

            versions = cls._schema_on_201.properties.versions
            versions.Element = AAZStrType()

            system_data = cls._schema_on_201.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",
            )

            return cls._schema_on_201

    class PolicyDefinitionsCreateOrUpdate(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(
                "/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}",
                **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(
                    "policyDefinitionName", self.ctx.args.name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2024-05-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,
                typ=AAZObjectType,
                typ_kwargs={"flags": {"required": True, "client_flatten": True}}
            )
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"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("metadata", AAZDictType, ".metadata")
                properties.set_prop("mode", AAZStrType, ".mode")
                properties.set_prop("parameters", AAZDictType, ".params")
                properties.set_prop("policyRule", AAZDictType, ".rules")
                properties.set_prop("version", AAZStrType, ".version")

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

            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", AAZAnyType, ".default_value")
                _elements.set_prop("metadata", AAZFreeFormDictType, ".metadata")
                _elements.set_prop("schema", AAZDictType, ".schema")
                _elements.set_prop("type", AAZStrType, ".type")

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

            metadata = _builder.get(".properties.parameters{}.metadata")
            if metadata is not None:
                metadata.set_anytype_elements(".")

            schema = _builder.get(".properties.parameters{}.schema")
            if schema is not None:
                schema.set_elements(AAZAnyType, ".")

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

            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()

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

            properties = cls._schema_on_201.properties
            properties.description = AAZStrType()
            properties.display_name = AAZStrType(
                serialized_name="displayName",
            )
            properties.metadata = AAZDictType()
            properties.mode = AAZStrType()
            properties.parameters = AAZDictType()
            properties.policy_rule = AAZDictType(
                serialized_name="policyRule",
            )
            properties.policy_type = AAZStrType(
                serialized_name="policyType",
            )
            properties.version = AAZStrType()
            properties.versions = AAZListType()

            metadata = cls._schema_on_201.properties.metadata
            metadata.Element = AAZAnyType()

            parameters = cls._schema_on_201.properties.parameters
            parameters.Element = AAZObjectType()

            _element = cls._schema_on_201.properties.parameters.Element
            _element.allowed_values = AAZListType(
                serialized_name="allowedValues",
            )
            _element.default_value = AAZAnyType(
                serialized_name="defaultValue",
            )
            _element.metadata = AAZFreeFormDictType()
            _element.schema = AAZDictType()
            _element.type = AAZStrType()

            allowed_values = cls._schema_on_201.properties.parameters.Element.allowed_values
            allowed_values.Element = AAZAnyType()

            schema = cls._schema_on_201.properties.parameters.Element.schema
            schema.Element = AAZAnyType()

            policy_rule = cls._schema_on_201.properties.policy_rule
            policy_rule.Element = AAZAnyType()

            versions = cls._schema_on_201.properties.versions
            versions.Element = AAZStrType()

            system_data = cls._schema_on_201.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",
            )

            return cls._schema_on_201


class _CreateHelper:
    """Helper class for Create"""


__all__ = ["Create"]
