# --------------------------------------------------------------------------------------------
# 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(
    "cdn origin create",
)
class Create(AAZCommand):
    """Create a new origin within the specified endpoint.

    :example: Create an additional origin
        az cdn origin create -g group --host-name example.contoso.com --profile-name profile --endpoint-name endpoint -n origin --host-name example.contoso.com --origin-host-header example.contoso.com --http-port 80 --https-port 443

    :example: Create a private origin
        az cdn origin create -g group --host-name example.contoso.com --profile-name profile --endpoint-name endpoint -n origin --http-port 80 --https-port 443 --private-link-resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group/providers/Microsoft.Network/privateLinkServices/pls --private-link-location EastUS --private-link-approval-message 'Please approve this request'
    """

    _aaz_info = {
        "version": "2023-05-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.cdn/profiles/{}/endpoints/{}/origins/{}", "2023-05-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.endpoint_name = AAZStrArg(
            options=["--endpoint-name"],
            help="Name of the endpoint under the profile which is unique globally.",
            required=True,
        )
        _args_schema.origin_name = AAZStrArg(
            options=["-n", "--name", "--origin-name"],
            help="Name of the origin that is unique within the endpoint.",
            required=True,
        )
        _args_schema.profile_name = AAZStrArg(
            options=["--profile-name"],
            help="Name of the CDN profile which is unique within the resource group.",
            required=True,
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.enabled = AAZBoolArg(
            options=["--enabled"],
            arg_group="Properties",
            help="Origin is enabled for load balancing or not",
        )
        _args_schema.host_name = AAZStrArg(
            options=["--host-name"],
            arg_group="Properties",
            help="The address of the origin. Domain names, IPv4 addresses, and IPv6 addresses are supported.This should be unique across all origins in an endpoint.",
        )
        _args_schema.http_port = AAZIntArg(
            options=["--http-port"],
            arg_group="Properties",
            help="The value of the HTTP port. Must be between 1 and 65535.",
            fmt=AAZIntArgFormat(
                maximum=65535,
                minimum=1,
            ),
        )
        _args_schema.https_port = AAZIntArg(
            options=["--https-port"],
            arg_group="Properties",
            help="The value of the HTTPS port. Must be between 1 and 65535.",
            fmt=AAZIntArgFormat(
                maximum=65535,
                minimum=1,
            ),
        )
        _args_schema.origin_host_header = AAZStrArg(
            options=["--origin-host-header"],
            arg_group="Properties",
            help="The host header value sent to the origin with each request. If you leave this blank, the request hostname determines this value. Azure CDN origins, such as Web Apps, Blob Storage, and Cloud Services require this host header value to match the origin hostname by default. This overrides the host header defined at Endpoint",
        )
        _args_schema.priority = AAZIntArg(
            options=["--priority"],
            arg_group="Properties",
            help="Priority of origin in given origin group for load balancing. Higher priorities will not be used for load balancing if any lower priority origin is healthy.Must be between 1 and 5",
            fmt=AAZIntArgFormat(
                maximum=5,
                minimum=1,
            ),
        )
        _args_schema.private_link_alias = AAZStrArg(
            options=["--private-link-alias"],
            arg_group="Properties",
            help="The Alias of the Private Link resource. Populating this optional field indicates that this origin is 'Private'",
        )
        _args_schema.private_link_approval_message = AAZStrArg(
            options=["-m", "--private-link-approval-message"],
            arg_group="Properties",
            help="A custom message to be included in the approval request to connect to the Private Link.",
        )
        _args_schema.private_link_location = AAZStrArg(
            options=["-l", "--private-link-location"],
            arg_group="Properties",
            help="The location of the Private Link resource. Required only if 'privateLinkResourceId' is populated",
        )
        _args_schema.private_link_resource_id = AAZStrArg(
            options=["-p", "--private-link-resource-id"],
            arg_group="Properties",
            help="The Resource Id of the Private Link resource. Populating this optional field indicates that this backend is 'Private'",
        )
        _args_schema.weight = AAZIntArg(
            options=["--weight"],
            arg_group="Properties",
            help="Weight of the origin in given origin group for load balancing. Must be between 1 and 1000",
            fmt=AAZIntArgFormat(
                maximum=1000,
                minimum=1,
            ),
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.OriginsCreate(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 OriginsCreate(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/Microsoft.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
                **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(
                    "endpointName", self.ctx.args.endpoint_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "originName", self.ctx.args.origin_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "profileName", self.ctx.args.profile_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-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("enabled", AAZBoolType, ".enabled")
                properties.set_prop("hostName", AAZStrType, ".host_name", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("httpPort", AAZIntType, ".http_port")
                properties.set_prop("httpsPort", AAZIntType, ".https_port")
                properties.set_prop("originHostHeader", AAZStrType, ".origin_host_header")
                properties.set_prop("priority", AAZIntType, ".priority")
                properties.set_prop("privateLinkAlias", AAZStrType, ".private_link_alias")
                properties.set_prop("privateLinkApprovalMessage", AAZStrType, ".private_link_approval_message")
                properties.set_prop("privateLinkLocation", AAZStrType, ".private_link_location")
                properties.set_prop("privateLinkResourceId", AAZStrType, ".private_link_resource_id")
                properties.set_prop("weight", AAZIntType, ".weight")

            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()
            _CreateHelper._build_schema_origin_read(cls._schema_on_200_201)

            return cls._schema_on_200_201


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

    _schema_origin_read = None

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

        cls._schema_origin_read = _schema_origin_read = AAZObjectType()

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

        properties = _schema_origin_read.properties
        properties.enabled = AAZBoolType()
        properties.host_name = AAZStrType(
            serialized_name="hostName",
            flags={"required": True},
        )
        properties.http_port = AAZIntType(
            serialized_name="httpPort",
        )
        properties.https_port = AAZIntType(
            serialized_name="httpsPort",
        )
        properties.origin_host_header = AAZStrType(
            serialized_name="originHostHeader",
        )
        properties.priority = AAZIntType()
        properties.private_endpoint_status = AAZStrType(
            serialized_name="privateEndpointStatus",
        )
        properties.private_link_alias = AAZStrType(
            serialized_name="privateLinkAlias",
        )
        properties.private_link_approval_message = AAZStrType(
            serialized_name="privateLinkApprovalMessage",
        )
        properties.private_link_location = AAZStrType(
            serialized_name="privateLinkLocation",
        )
        properties.private_link_resource_id = AAZStrType(
            serialized_name="privateLinkResourceId",
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.resource_state = AAZStrType(
            serialized_name="resourceState",
            flags={"read_only": True},
        )
        properties.weight = AAZIntType()

        system_data = _schema_origin_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.id = cls._schema_origin_read.id
        _schema.name = cls._schema_origin_read.name
        _schema.properties = cls._schema_origin_read.properties
        _schema.system_data = cls._schema_origin_read.system_data
        _schema.type = cls._schema_origin_read.type


__all__ = ["Create"]
