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

    :example: Create a registration definition under the default subscription scope with the required parameters.
        az managedservices definition create --name mydef --tenant-id dab3375b-6197-4a15-a44b-16c41faa91d7 --principal-id b6f6c88a-5b7a-455e-ba40-ce146d4d3671 --role-definition-id ccdd72a7-3385-48ef-bd42-f606fba81ae7
    """

    _aaz_info = {
        "version": "2019-06-01",
        "resources": [
            ["mgmt-plane", "/{scope}/providers/microsoft.managedservices/registrationdefinitions/{}", "2019-06-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = 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.definition_id = AAZStrArg(
            options=["--definition-id"],
            help="Guid of the registration definition.",
            required=True,
        )
        _args_schema.scope = AAZStrArg(
            options=["--scope"],
            help="Scope of the resource.",
            required=True,
        )
        _args_schema.plan_name = AAZStrArg(
            options=["--plan-name"],
            help="The plan name.",
        )
        _args_schema.plan_product = AAZStrArg(
            options=["--plan-product"],
            help="The product code.",
        )
        _args_schema.plan_publisher = AAZStrArg(
            options=["--plan-publisher"],
            help="The publisher ID.",
        )
        _args_schema.plan_version = AAZStrArg(
            options=["--plan-version"],
            help="The plan's version.",
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            help="Description of the registration definition.",
        )
        _args_schema.tenant_id = AAZStrArg(
            options=["--tenant-id"],
            help="Id of the managedBy tenant.",
        )
        _args_schema.name = AAZStrArg(
            options=["--name"],
            help="Name of the registration definition.",
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.authorizations = AAZListArg(
            options=["--authorizations"],
            arg_group="Properties",
            help="Authorization tuple containing principal id of the user/security group or service principal and id of the build-in role.",
        )

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

        _element = cls._args_schema.authorizations.Element
        _element.delegated_role_definition_ids = AAZListArg(
            options=["delegated-role-definition-ids"],
            help="The delegatedRoleDefinitionIds field is required when the roleDefinitionId refers to the User Access Administrator Role. It is the list of role definition ids which define all the permissions that the user in the authorization can assign to other security groups/service principals/users.",
        )
        _element.principal_id = AAZStrArg(
            options=["principal-id"],
            help="Principal Id of the security group/service principal/user that would be assigned permissions to the projected subscription",
            required=True,
        )
        _element.principal_id_display_name = AAZStrArg(
            options=["principal-id-display-name"],
            help="Display name of the principal Id.",
        )
        _element.role_definition_id = AAZStrArg(
            options=["role-definition-id"],
            help="The role definition identifier. This role will define all the permissions that the security group/service principal/user must have on the projected subscription. This role cannot be an owner role.",
            required=True,
        )

        delegated_role_definition_ids = cls._args_schema.authorizations.Element.delegated_role_definition_ids
        delegated_role_definition_ids.Element = AAZUuidArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.RegistrationDefinitionsCreateOrUpdate(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 RegistrationDefinitionsCreateOrUpdate(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": "azure-async-operation"},
                    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": "azure-async-operation"},
                    path_format_arguments=self.url_parameters,
                )

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}",
                **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(
                    "registrationDefinitionId", self.ctx.args.definition_id,
                    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", "2019-06-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("plan", AAZObjectType)
            _builder.set_prop("properties", AAZObjectType)

            plan = _builder.get(".plan")
            if plan is not None:
                plan.set_prop("name", AAZStrType, ".plan_name", typ_kwargs={"flags": {"required": True}})
                plan.set_prop("product", AAZStrType, ".plan_product", typ_kwargs={"flags": {"required": True}})
                plan.set_prop("publisher", AAZStrType, ".plan_publisher", typ_kwargs={"flags": {"required": True}})
                plan.set_prop("version", AAZStrType, ".plan_version", typ_kwargs={"flags": {"required": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("authorizations", AAZListType, ".authorizations", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("managedByTenantId", AAZStrType, ".tenant_id", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("registrationDefinitionName", AAZStrType, ".name")

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

            _elements = _builder.get(".properties.authorizations[]")
            if _elements is not None:
                _elements.set_prop("delegatedRoleDefinitionIds", AAZListType, ".delegated_role_definition_ids")
                _elements.set_prop("principalId", AAZStrType, ".principal_id", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("principalIdDisplayName", AAZStrType, ".principal_id_display_name")
                _elements.set_prop("roleDefinitionId", AAZStrType, ".role_definition_id", typ_kwargs={"flags": {"required": True}})

            delegated_role_definition_ids = _builder.get(".properties.authorizations[].delegatedRoleDefinitionIds")
            if delegated_role_definition_ids is not None:
                delegated_role_definition_ids.set_elements(AAZStrType, ".")

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

            _schema_on_200_201 = cls._schema_on_200_201
            _schema_on_200_201.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.plan = AAZObjectType()
            _schema_on_200_201.properties = AAZObjectType()
            _schema_on_200_201.type = AAZStrType(
                flags={"read_only": True},
            )

            plan = cls._schema_on_200_201.plan
            plan.name = AAZStrType(
                flags={"required": True},
            )
            plan.product = AAZStrType(
                flags={"required": True},
            )
            plan.publisher = AAZStrType(
                flags={"required": True},
            )
            plan.version = AAZStrType(
                flags={"required": True},
            )

            properties = cls._schema_on_200_201.properties
            properties.authorizations = AAZListType(
                flags={"required": True},
            )
            properties.description = AAZStrType()
            properties.managed_by_tenant_id = AAZStrType(
                serialized_name="managedByTenantId",
                flags={"required": True},
            )
            properties.managed_by_tenant_name = AAZStrType(
                serialized_name="managedByTenantName",
                flags={"read_only": True},
            )
            properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
                flags={"read_only": True},
            )
            properties.registration_definition_name = AAZStrType(
                serialized_name="registrationDefinitionName",
            )

            authorizations = cls._schema_on_200_201.properties.authorizations
            authorizations.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.authorizations.Element
            _element.delegated_role_definition_ids = AAZListType(
                serialized_name="delegatedRoleDefinitionIds",
            )
            _element.principal_id = AAZStrType(
                serialized_name="principalId",
                flags={"required": True},
            )
            _element.principal_id_display_name = AAZStrType(
                serialized_name="principalIdDisplayName",
            )
            _element.role_definition_id = AAZStrType(
                serialized_name="roleDefinitionId",
                flags={"required": True},
            )

            delegated_role_definition_ids = cls._schema_on_200_201.properties.authorizations.Element.delegated_role_definition_ids
            delegated_role_definition_ids.Element = AAZStrType()

            return cls._schema_on_200_201


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


__all__ = ["Create"]
