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

    :example: Update an origin
        az cdn origin update -g group --profile-name profile --endpoint-name endpoint -n origin --http-port 80 --https-port 443 --priority 3 --weight 500 --host-name example.contoso.com

    :example: Disable an origin
        az cdn origin update -g group --profile-name profile --endpoint-name endpoint -n origin --disabled

    :example: Connect an origin to a private link service
        az cdn origin update -g group --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": "2024-09-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.cdn/profiles/{}/endpoints/{}/origins/{}", "2024-09-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = True

    AZ_SUPPORT_GENERIC_UPDATE = 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,
            id_part="child_name_1",
        )
        _args_schema.origin_name = AAZStrArg(
            options=["-n", "--name", "--origin-name"],
            help="Name of the origin which is unique within the endpoint.",
            required=True,
            id_part="child_name_2",
        )
        _args_schema.profile_name = AAZStrArg(
            options=["--profile-name"],
            help="Name of the CDN profile which is unique within the resource group.",
            required=True,
            id_part="name",
        )
        _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",
            nullable=True,
        )
        _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.",
            nullable=True,
            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.",
            nullable=True,
            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",
            nullable=True,
        )
        _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",
            nullable=True,
            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'",
            nullable=True,
        )
        _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.",
            nullable=True,
        )
        _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",
            nullable=True,
        )
        _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'",
            nullable=True,
        )
        _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",
            nullable=True,
            fmt=AAZIntArgFormat(
                maximum=1000,
                minimum=1,
            ),
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.OriginsGet(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)
        yield self.OriginsCreate(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 OriginsGet(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.Cdn/profiles/{profileName}/endpoints/{endpointName}/origins/{originName}",
                **self.url_parameters
            )

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

        @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", "2024-09-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_origin_read(cls._schema_on_200)

            return cls._schema_on_200

    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", "2024-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,
                value=self.ctx.vars.instance,
            )

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

            return cls._schema_on_200_201

    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("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 _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"""

    _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",
            flags={"read_only": True},
        )
        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__ = ["Update"]
