# --------------------------------------------------------------------------------------------
# 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(
    "devcenter admin project-environment-type update",
)
class Update(AAZCommand):
    """Update a project environment type.

    :example: Update
        az devcenter admin project-environment-type update --identity-type "UserAssigned" --user-assigned-identities "{\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/identityGroup/providers/Microsoft.ManagedIdentity/userAssignedIdentities/testidentity1\":{}}" --deployment-target-id "/subscriptions/00000000-0000-0000-0000-000000000000" --status "Enabled" --user-role-assignments "{\"e45e3m7c-176e-416a-b466-0c5ec8298f8a\":{\"roles\":{\"4cbf0b6c-e750-441c-98a7-10da8387e4d6\":{}}}}" --tags CostCenter="RnD" --environment-type-name "DevTest" --project-name "ContosoProj" --resource-group "rg1"
    """

    _aaz_info = {
        "version": "2023-04-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.devcenter/projects/{}/environmenttypes/{}", "2023-04-01"],
        ]
    }

    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.environment_type_name = AAZStrArg(
            options=["-n", "--name", "--environment-type-name"],
            help="The name of the environment type.",
            required=True,
            id_part="child_name_1",
        )
        _args_schema.project_name = AAZStrArg(
            options=["--project", "--project-name"],
            help="The name of the project. Use `az configure -d project=<project_name>` to configure a default.",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            help="Name of resource group. You can configure the default group using `az configure --defaults group=<name>`.",
            required=True,
        )

        # define Arg Group "Body"

        _args_schema = cls._args_schema
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            arg_group="Body",
            help="Resource tags.",
            nullable=True,
        )

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

        # define Arg Group "CreatorRoleAssignment"

        _args_schema = cls._args_schema
        _args_schema.roles = AAZDictArg(
            options=["--roles"],
            arg_group="CreatorRoleAssignment",
            help="A map of roles to assign to the environment creator.",
            nullable=True,
        )

        roles = cls._args_schema.roles
        roles.Element = AAZObjectArg(
            nullable=True,
            blank={},
        )
        cls._build_args_environment_role_update(roles.Element)

        # define Arg Group "Identity"

        _args_schema = cls._args_schema
        _args_schema.identity_type = AAZStrArg(
            options=["--identity-type"],
            arg_group="Identity",
            help="Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed).",
            enum={"None": "None", "SystemAssigned": "SystemAssigned", "SystemAssigned, UserAssigned": "SystemAssigned, UserAssigned", "UserAssigned": "UserAssigned"},
        )
        _args_schema.user_assigned_identities = AAZDictArg(
            options=["-u", "--user-assigned-identities"],
            arg_group="Identity",
            help="The set of user assigned identities associated with the resource. The userAssignedIdentities dictionary keys will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}. The dictionary values can be empty objects ({}) in requests.",
            nullable=True,
        )

        user_assigned_identities = cls._args_schema.user_assigned_identities
        user_assigned_identities.Element = AAZObjectArg(
            nullable=True,
            blank={},
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.deployment_target_id = AAZStrArg(
            options=["--deployment-target-id"],
            arg_group="Properties",
            help="ID of a subscription that the environment type will be mapped to. The environment's resources will be deployed into this subscription.",
            nullable=True,
        )
        _args_schema.status = AAZStrArg(
            options=["--status"],
            arg_group="Properties",
            help="Defines whether this environment type can be used in this project.",
            nullable=True,
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        _args_schema.user_role_assignments = AAZDictArg(
            options=["--user-role-assignments"],
            arg_group="Properties",
            help="Role assignments created on environment backing resources. This is a mapping from a user object ID to an object of role definition IDs.",
            nullable=True,
        )

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

        _element = cls._args_schema.user_role_assignments.Element
        _element.roles = AAZDictArg(
            options=["roles"],
            help="A map of roles to assign to the parent user.",
            nullable=True,
        )

        roles = cls._args_schema.user_role_assignments.Element.roles
        roles.Element = AAZObjectArg(
            nullable=True,
            blank={},
        )
        cls._build_args_environment_role_update(roles.Element)
        return cls._args_schema

    _args_environment_role_update = None

    @classmethod
    def _build_args_environment_role_update(cls, _schema):
        if cls._args_environment_role_update is not None:
            return

        cls._args_environment_role_update = AAZObjectArg(
            nullable=True,
            blank={},
        )


    def _execute_operations(self):
        self.pre_operations()
        self.ProjectEnvironmentTypesGet(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.ProjectEnvironmentTypesCreateOrUpdate(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 ProjectEnvironmentTypesGet(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(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/environmentTypes/{environmentTypeName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "environmentTypeName", self.ctx.args.environment_type_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "projectName", self.ctx.args.project_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    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", "2023-04-01",
                    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_project_environment_type_read(cls._schema_on_200)

            return cls._schema_on_200

    class ProjectEnvironmentTypesCreateOrUpdate(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(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DevCenter/projects/{projectName}/environmentTypes/{environmentTypeName}",
                **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(
                    "environmentTypeName", self.ctx.args.environment_type_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "projectName", self.ctx.args.project_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    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", "2023-04-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,
                value=self.ctx.vars.instance,
            )

            return self.serialize_content(_content_value)

        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_project_environment_type_read(cls._schema_on_200)

            return cls._schema_on_200

    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("identity", AAZObjectType)
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            identity = _builder.get(".identity")
            if identity is not None:
                identity.set_prop("type", AAZStrType, ".identity_type", typ_kwargs={"flags": {"required": True}})
                identity.set_prop("userAssignedIdentities", AAZDictType, ".user_assigned_identities")

            user_assigned_identities = _builder.get(".identity.userAssignedIdentities")
            if user_assigned_identities is not None:
                user_assigned_identities.set_elements(AAZObjectType, ".")

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("creatorRoleAssignment", AAZObjectType)
                properties.set_prop("deploymentTargetId", AAZStrType, ".deployment_target_id")
                properties.set_prop("status", AAZStrType, ".status")
                properties.set_prop("userRoleAssignments", AAZDictType, ".user_role_assignments")

            creator_role_assignment = _builder.get(".properties.creatorRoleAssignment")
            if creator_role_assignment is not None:
                creator_role_assignment.set_prop("roles", AAZDictType, ".roles")

            roles = _builder.get(".properties.creatorRoleAssignment.roles")
            if roles is not None:
                _UpdateHelper._build_schema_environment_role_update(roles.set_elements(AAZObjectType, "."))

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

            _elements = _builder.get(".properties.userRoleAssignments{}")
            if _elements is not None:
                _elements.set_prop("roles", AAZDictType, ".roles")

            roles = _builder.get(".properties.userRoleAssignments{}.roles")
            if roles is not None:
                _UpdateHelper._build_schema_environment_role_update(roles.set_elements(AAZObjectType, "."))

            tags = _builder.get(".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"""

    @classmethod
    def _build_schema_environment_role_update(cls, _builder):
        if _builder is None:
            return

    _schema_environment_role_read = None

    @classmethod
    def _build_schema_environment_role_read(cls, _schema):
        if cls._schema_environment_role_read is not None:
            _schema.description = cls._schema_environment_role_read.description
            _schema.role_name = cls._schema_environment_role_read.role_name
            return

        cls._schema_environment_role_read = _schema_environment_role_read = AAZObjectType()

        environment_role_read = _schema_environment_role_read
        environment_role_read.description = AAZStrType(
            flags={"read_only": True},
        )
        environment_role_read.role_name = AAZStrType(
            serialized_name="roleName",
            flags={"read_only": True},
        )

        _schema.description = cls._schema_environment_role_read.description
        _schema.role_name = cls._schema_environment_role_read.role_name

    _schema_project_environment_type_read = None

    @classmethod
    def _build_schema_project_environment_type_read(cls, _schema):
        if cls._schema_project_environment_type_read is not None:
            _schema.id = cls._schema_project_environment_type_read.id
            _schema.identity = cls._schema_project_environment_type_read.identity
            _schema.location = cls._schema_project_environment_type_read.location
            _schema.name = cls._schema_project_environment_type_read.name
            _schema.properties = cls._schema_project_environment_type_read.properties
            _schema.system_data = cls._schema_project_environment_type_read.system_data
            _schema.tags = cls._schema_project_environment_type_read.tags
            _schema.type = cls._schema_project_environment_type_read.type
            return

        cls._schema_project_environment_type_read = _schema_project_environment_type_read = AAZObjectType()

        project_environment_type_read = _schema_project_environment_type_read
        project_environment_type_read.id = AAZStrType(
            flags={"read_only": True},
        )
        project_environment_type_read.identity = AAZObjectType()
        project_environment_type_read.location = AAZStrType()
        project_environment_type_read.name = AAZStrType(
            flags={"read_only": True},
        )
        project_environment_type_read.properties = AAZObjectType(
            flags={"client_flatten": True},
        )
        project_environment_type_read.system_data = AAZObjectType(
            serialized_name="systemData",
            flags={"read_only": True},
        )
        project_environment_type_read.tags = AAZDictType()
        project_environment_type_read.type = AAZStrType(
            flags={"read_only": True},
        )

        identity = _schema_project_environment_type_read.identity
        identity.principal_id = AAZStrType(
            serialized_name="principalId",
            flags={"read_only": True},
        )
        identity.tenant_id = AAZStrType(
            serialized_name="tenantId",
            flags={"read_only": True},
        )
        identity.type = AAZStrType(
            flags={"required": True},
        )
        identity.user_assigned_identities = AAZDictType(
            serialized_name="userAssignedIdentities",
        )

        user_assigned_identities = _schema_project_environment_type_read.identity.user_assigned_identities
        user_assigned_identities.Element = AAZObjectType()

        _element = _schema_project_environment_type_read.identity.user_assigned_identities.Element
        _element.client_id = AAZStrType(
            serialized_name="clientId",
            flags={"read_only": True},
        )
        _element.principal_id = AAZStrType(
            serialized_name="principalId",
            flags={"read_only": True},
        )

        properties = _schema_project_environment_type_read.properties
        properties.creator_role_assignment = AAZObjectType(
            serialized_name="creatorRoleAssignment",
        )
        properties.deployment_target_id = AAZStrType(
            serialized_name="deploymentTargetId",
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.status = AAZStrType()
        properties.user_role_assignments = AAZDictType(
            serialized_name="userRoleAssignments",
        )

        creator_role_assignment = _schema_project_environment_type_read.properties.creator_role_assignment
        creator_role_assignment.roles = AAZDictType()

        roles = _schema_project_environment_type_read.properties.creator_role_assignment.roles
        roles.Element = AAZObjectType()
        cls._build_schema_environment_role_read(roles.Element)

        user_role_assignments = _schema_project_environment_type_read.properties.user_role_assignments
        user_role_assignments.Element = AAZObjectType()

        _element = _schema_project_environment_type_read.properties.user_role_assignments.Element
        _element.roles = AAZDictType()

        roles = _schema_project_environment_type_read.properties.user_role_assignments.Element.roles
        roles.Element = AAZObjectType()
        cls._build_schema_environment_role_read(roles.Element)

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

        tags = _schema_project_environment_type_read.tags
        tags.Element = AAZStrType()

        _schema.id = cls._schema_project_environment_type_read.id
        _schema.identity = cls._schema_project_environment_type_read.identity
        _schema.location = cls._schema_project_environment_type_read.location
        _schema.name = cls._schema_project_environment_type_read.name
        _schema.properties = cls._schema_project_environment_type_read.properties
        _schema.system_data = cls._schema_project_environment_type_read.system_data
        _schema.tags = cls._schema_project_environment_type_read.tags
        _schema.type = cls._schema_project_environment_type_read.type


__all__ = ["Update"]
