# --------------------------------------------------------------------------------------------
# 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(
    "dynatrace monitor create"
)
class Create(AAZCommand):
    """Create a monitor resource

    :example: Create a monitor
        az dynatrace monitor create -g rg -n monitor --user-info "{first-name:Alice,last-name:Bobab,email-address:Alice@microsoft.com,phone-number:1234567890,country:US}" --plan-data "{usage-type:committed,billing-cycle:Monthly,plan-details:azureportalintegration_privatepreview@TIDhjdtn7tfnxcy,effective-date:2022-08-20}" --environment "{single-sign-on:{aad-domains:['abc']}}"
    """

    _aaz_info = {
        "version": "2021-09-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/dynatrace.observability/monitors/{}", "2021-09-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.monitor_name = AAZStrArg(
            options=["-n", "--name", "--monitor-name"],
            help="Monitor resource name",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.environment = AAZObjectArg(
            options=["--environment"],
            arg_group="Properties",
            help="Properties of the Dynatrace environment.",
        )
        _args_schema.subscription_status = AAZStrArg(
            options=["--subscription-status"],
            arg_group="Properties",
            help="Marketplace subscription status.",
            enum={"Active": "Active", "Suspended": "Suspended"},
        )
        _args_schema.monitoring_status = AAZStrArg(
            options=["--monitoring-status"],
            arg_group="Properties",
            help="Status of the monitor.",
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        _args_schema.plan_data = AAZObjectArg(
            options=["--plan-data"],
            arg_group="Properties",
            help="Billing plan information.",
        )
        _args_schema.user_info = AAZObjectArg(
            options=["--user-info"],
            arg_group="Properties",
            help="User info.",
        )

        environment = cls._args_schema.environment
        environment.account_info = AAZObjectArg(
            options=["account-info"],
            help="Dynatrace Account Information",
        )
        environment.environment_info = AAZObjectArg(
            options=["environment-info"],
            help="Dynatrace Environment Information",
        )
        environment.single_sign_on = AAZObjectArg(
            options=["single-sign-on"],
            help="The details of a Dynatrace single sign-on.",
        )
        environment.user_id = AAZStrArg(
            options=["user-id"],
            help="User id",
        )

        account_info = cls._args_schema.environment.account_info
        account_info.account_id = AAZStrArg(
            options=["account-id"],
            help="Account Id of the account this environment is linked to",
        )
        account_info.region_id = AAZStrArg(
            options=["region-id"],
            help="Region in which the account is created",
        )

        environment_info = cls._args_schema.environment.environment_info
        environment_info.environment_id = AAZStrArg(
            options=["environment-id"],
            help="Id of the environment created",
        )
        environment_info.ingestion_key = AAZStrArg(
            options=["ingestion-key"],
            help="Ingestion key of the environment",
        )
        environment_info.landing_url = AAZStrArg(
            options=["landing-url"],
            help="Landing URL for Dynatrace environment",
        )
        environment_info.logs_ingestion_endpoint = AAZStrArg(
            options=["logs-ingestion-endpoint"],
            help="Ingestion endpoint used for sending logs",
        )

        single_sign_on = cls._args_schema.environment.single_sign_on
        single_sign_on.aad_domains = AAZListArg(
            options=["aad-domains"],
            help="array of Aad(azure active directory) domains",
        )
        single_sign_on.enterprise_app_id = AAZStrArg(
            options=["enterprise-app-id"],
            help="Version of the Dynatrace agent installed on the VM.",
        )
        single_sign_on.single_sign_on_state = AAZStrArg(
            options=["single-sign-on-state"],
            help="State of Single Sign On",
            enum={"Disable": "Disable", "Enable": "Enable", "Existing": "Existing", "Initial": "Initial"},
        )
        single_sign_on.single_sign_on_url = AAZStrArg(
            options=["single-sign-on-url"],
            help="The login URL specific to this Dynatrace Environment",
        )

        aad_domains = cls._args_schema.environment.single_sign_on.aad_domains
        aad_domains.Element = AAZStrArg()

        plan_data = cls._args_schema.plan_data
        plan_data.billing_cycle = AAZStrArg(
            options=["billing-cycle"],
            help="different billing cycles like MONTHLY/WEEKLY. this could be enum",
        )
        plan_data.effective_date = AAZDateTimeArg(
            options=["effective-date"],
            help="date when plan was applied",
        )
        plan_data.plan_details = AAZStrArg(
            options=["plan-details"],
            help="plan id as published by Dynatrace",
        )
        plan_data.usage_type = AAZStrArg(
            options=["usage-type"],
            help="different usage type like PAYG/COMMITTED. this could be enum",
        )

        user_info = cls._args_schema.user_info
        user_info.country = AAZStrArg(
            options=["country"],
            help="Country of the user",
        )
        user_info.email_address = AAZStrArg(
            options=["email-address"],
            help="Email of the user used by Dynatrace for contacting them if needed",
            fmt=AAZStrArgFormat(
                pattern="^[A-Za-z0-9._%+-]+@(?:[A-Za-z0-9-]+\.)+[A-Za-z]{2,}$",
            ),
        )
        user_info.first_name = AAZStrArg(
            options=["first-name"],
            help="First Name of the user",
        )
        user_info.last_name = AAZStrArg(
            options=["last-name"],
            help="Last Name of the user",
        )
        user_info.phone_number = AAZStrArg(
            options=["phone-number"],
            help="Phone number of the user used by Dynatrace for contacting them if needed",
            fmt=AAZStrArgFormat(
                max_length=40,
            ),
        )

        # define Arg Group "Resource"

        _args_schema = cls._args_schema
        _args_schema.identity = AAZObjectArg(
            options=["--identity"],
            arg_group="Resource",
            help="The managed service identities assigned to this resource.",
        )
        _args_schema.location = AAZResourceLocationArg(
            arg_group="Resource",
            help="The geo-location where the resource lives",
            required=True,
            fmt=AAZResourceLocationArgFormat(
                resource_group_arg="resource_group",
            ),
        )
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            arg_group="Resource",
            help="Resource tags.",
        )

        identity = cls._args_schema.identity
        identity.type = AAZStrArg(
            options=["type"],
            help="The type of managed identity assigned to this resource.",
            required=True,
            enum={"SystemAndUserAssigned": "SystemAndUserAssigned", "SystemAssigned": "SystemAssigned", "UserAssigned": "UserAssigned"},
        )
        identity.user_assigned_identities = AAZDictArg(
            options=["user-assigned-identities"],
            help="The identities assigned to this resource by the user.",
        )

        user_assigned_identities = cls._args_schema.identity.user_assigned_identities
        user_assigned_identities.Element = AAZObjectArg()

        _element = cls._args_schema.identity.user_assigned_identities.Element
        _element.client_id = AAZStrArg(
            options=["client-id"],
            help="The active directory client identifier for this principal.",
            required=True,
        )
        _element.principal_id = AAZStrArg(
            options=["principal-id"],
            help="The active directory identifier for this principal.",
            required=True,
        )

        tags = cls._args_schema.tags
        tags.Element = AAZStrArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.MonitorsCreateOrUpdate(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 MonitorsCreateOrUpdate(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(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Dynatrace.Observability/monitors/{monitorName}",
                **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(
                    "monitorName", self.ctx.args.monitor_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", "2021-09-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("identity", AAZObjectType, ".identity")
            _builder.set_prop("location", AAZStrType, ".location", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("properties", AAZObjectType, ".", typ_kwargs={"flags": {"required": True, "client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            identity = _builder.get(".identity")
            if identity is not None:
                identity.set_prop("type", AAZStrType, ".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, ".")

            _elements = _builder.get(".identity.userAssignedIdentities{}")
            if _elements is not None:
                _elements.set_prop("clientId", AAZStrType, ".client_id", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("principalId", AAZStrType, ".principal_id", typ_kwargs={"flags": {"required": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("dynatraceEnvironmentProperties", AAZObjectType, ".environment")
                properties.set_prop("marketplaceSubscriptionStatus", AAZStrType, ".subscription_status")
                properties.set_prop("monitoringStatus", AAZStrType, ".monitoring_status")
                properties.set_prop("planData", AAZObjectType, ".plan_data")
                properties.set_prop("userInfo", AAZObjectType, ".user_info")

            dynatrace_environment_properties = _builder.get(".properties.dynatraceEnvironmentProperties")
            if dynatrace_environment_properties is not None:
                dynatrace_environment_properties.set_prop("accountInfo", AAZObjectType, ".account_info")
                dynatrace_environment_properties.set_prop("environmentInfo", AAZObjectType, ".environment_info")
                dynatrace_environment_properties.set_prop("singleSignOnProperties", AAZObjectType, ".single_sign_on")
                dynatrace_environment_properties.set_prop("userId", AAZStrType, ".user_id")

            account_info = _builder.get(".properties.dynatraceEnvironmentProperties.accountInfo")
            if account_info is not None:
                account_info.set_prop("accountId", AAZStrType, ".account_id")
                account_info.set_prop("regionId", AAZStrType, ".region_id")

            environment_info = _builder.get(".properties.dynatraceEnvironmentProperties.environmentInfo")
            if environment_info is not None:
                environment_info.set_prop("environmentId", AAZStrType, ".environment_id")
                environment_info.set_prop("ingestionKey", AAZStrType, ".ingestion_key")
                environment_info.set_prop("landingURL", AAZStrType, ".landing_url")
                environment_info.set_prop("logsIngestionEndpoint", AAZStrType, ".logs_ingestion_endpoint")

            single_sign_on_properties = _builder.get(".properties.dynatraceEnvironmentProperties.singleSignOnProperties")
            if single_sign_on_properties is not None:
                single_sign_on_properties.set_prop("aadDomains", AAZListType, ".aad_domains")
                single_sign_on_properties.set_prop("enterpriseAppId", AAZStrType, ".enterprise_app_id")
                single_sign_on_properties.set_prop("singleSignOnState", AAZStrType, ".single_sign_on_state")
                single_sign_on_properties.set_prop("singleSignOnUrl", AAZStrType, ".single_sign_on_url")

            aad_domains = _builder.get(".properties.dynatraceEnvironmentProperties.singleSignOnProperties.aadDomains")
            if aad_domains is not None:
                aad_domains.set_elements(AAZStrType, ".")

            plan_data = _builder.get(".properties.planData")
            if plan_data is not None:
                plan_data.set_prop("billingCycle", AAZStrType, ".billing_cycle")
                plan_data.set_prop("effectiveDate", AAZStrType, ".effective_date")
                plan_data.set_prop("planDetails", AAZStrType, ".plan_details")
                plan_data.set_prop("usageType", AAZStrType, ".usage_type")

            user_info = _builder.get(".properties.userInfo")
            if user_info is not None:
                user_info.set_prop("country", AAZStrType, ".country")
                user_info.set_prop("emailAddress", AAZStrType, ".email_address")
                user_info.set_prop("firstName", AAZStrType, ".first_name")
                user_info.set_prop("lastName", AAZStrType, ".last_name")
                user_info.set_prop("phoneNumber", AAZStrType, ".phone_number")

            tags = _builder.get(".tags")
            if tags is not None:
                tags.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.identity = AAZObjectType()
            _schema_on_200_201.location = AAZStrType(
                flags={"required": True},
            )
            _schema_on_200_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.properties = AAZObjectType(
                flags={"required": True, "client_flatten": True},
            )
            _schema_on_200_201.system_data = AAZObjectType(
                serialized_name="systemData",
                flags={"read_only": True},
            )
            _schema_on_200_201.tags = AAZDictType()
            _schema_on_200_201.type = AAZStrType(
                flags={"read_only": True},
            )

            identity = cls._schema_on_200_201.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 = cls._schema_on_200_201.identity.user_assigned_identities
            user_assigned_identities.Element = AAZObjectType()

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

            properties = cls._schema_on_200_201.properties
            properties.dynatrace_environment_properties = AAZObjectType(
                serialized_name="dynatraceEnvironmentProperties",
            )
            properties.liftr_resource_category = AAZStrType(
                serialized_name="liftrResourceCategory",
            )
            properties.liftr_resource_preference = AAZIntType(
                serialized_name="liftrResourcePreference",
                flags={"read_only": True},
            )
            properties.marketplace_subscription_status = AAZStrType(
                serialized_name="marketplaceSubscriptionStatus",
            )
            properties.monitoring_status = AAZStrType(
                serialized_name="monitoringStatus",
            )
            properties.plan_data = AAZObjectType(
                serialized_name="planData",
            )
            properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
            )
            properties.user_info = AAZObjectType(
                serialized_name="userInfo",
            )

            dynatrace_environment_properties = cls._schema_on_200_201.properties.dynatrace_environment_properties
            dynatrace_environment_properties.account_info = AAZObjectType(
                serialized_name="accountInfo",
            )
            dynatrace_environment_properties.environment_info = AAZObjectType(
                serialized_name="environmentInfo",
            )
            dynatrace_environment_properties.single_sign_on_properties = AAZObjectType(
                serialized_name="singleSignOnProperties",
            )
            dynatrace_environment_properties.user_id = AAZStrType(
                serialized_name="userId",
            )

            account_info = cls._schema_on_200_201.properties.dynatrace_environment_properties.account_info
            account_info.account_id = AAZStrType(
                serialized_name="accountId",
            )
            account_info.region_id = AAZStrType(
                serialized_name="regionId",
            )

            environment_info = cls._schema_on_200_201.properties.dynatrace_environment_properties.environment_info
            environment_info.environment_id = AAZStrType(
                serialized_name="environmentId",
            )
            environment_info.ingestion_key = AAZStrType(
                serialized_name="ingestionKey",
            )
            environment_info.landing_url = AAZStrType(
                serialized_name="landingURL",
            )
            environment_info.logs_ingestion_endpoint = AAZStrType(
                serialized_name="logsIngestionEndpoint",
            )

            single_sign_on_properties = cls._schema_on_200_201.properties.dynatrace_environment_properties.single_sign_on_properties
            single_sign_on_properties.aad_domains = AAZListType(
                serialized_name="aadDomains",
            )
            single_sign_on_properties.enterprise_app_id = AAZStrType(
                serialized_name="enterpriseAppId",
            )
            single_sign_on_properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
            )
            single_sign_on_properties.single_sign_on_state = AAZStrType(
                serialized_name="singleSignOnState",
            )
            single_sign_on_properties.single_sign_on_url = AAZStrType(
                serialized_name="singleSignOnUrl",
            )

            aad_domains = cls._schema_on_200_201.properties.dynatrace_environment_properties.single_sign_on_properties.aad_domains
            aad_domains.Element = AAZStrType()

            plan_data = cls._schema_on_200_201.properties.plan_data
            plan_data.billing_cycle = AAZStrType(
                serialized_name="billingCycle",
            )
            plan_data.effective_date = AAZStrType(
                serialized_name="effectiveDate",
            )
            plan_data.plan_details = AAZStrType(
                serialized_name="planDetails",
            )
            plan_data.usage_type = AAZStrType(
                serialized_name="usageType",
            )

            user_info = cls._schema_on_200_201.properties.user_info
            user_info.country = AAZStrType()
            user_info.email_address = AAZStrType(
                serialized_name="emailAddress",
            )
            user_info.first_name = AAZStrType(
                serialized_name="firstName",
            )
            user_info.last_name = AAZStrType(
                serialized_name="lastName",
            )
            user_info.phone_number = AAZStrType(
                serialized_name="phoneNumber",
            )

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

            tags = cls._schema_on_200_201.tags
            tags.Element = AAZStrType()

            return cls._schema_on_200_201


__all__ = ["Create"]
