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

    :example: Update the host header and priority of the specified origin.
        az afd origin update -g group --host-name example.contoso.com --profile-name profile --origin-group-name originGroup --origin-name origin1 --origin-host-header example.contoso.com --priority 3

    :example: Disable private link of the origin.
        az afd origin update -g group --host-name example.contoso.com --profile-name profile --origin-group-name originGroup --origin-name origin1 --enable-private-link False
    """

    _aaz_info = {
        "version": "2025-06-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.cdn/profiles/{}/origingroups/{}/origins/{}", "2025-06-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.origin_group_name = AAZStrArg(
            options=["--origin-group-name"],
            help="Name of the origin group which is unique within the profile.",
            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 profile.",
            required=True,
            id_part="child_name_2",
        )
        _args_schema.profile_name = AAZStrArg(
            options=["--profile-name"],
            help="Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique within the resource group.",
            required=True,
            id_part="name",
            fmt=AAZStrArgFormat(
                pattern="^[a-zA-Z0-9]+(-*[a-zA-Z0-9])*$",
                max_length=260,
                min_length=1,
            ),
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.enabled_state = AAZStrArg(
            options=["--enabled-state"],
            arg_group="Properties",
            help="Whether to enable health probes to be made against backends defined under backendPools. Health probes can only be disabled if there is a single enabled backend in single enabled backend pool. When an origin is disabled, both routing and health probes to the origin are also disabled.",
            nullable=True,
            enum={"Disabled": "Disabled", "Enabled": "Enabled"},
        )
        _args_schema.enforce_certificate_name_check = AAZBoolArg(
            options=["--enforce-certificate-name-check"],
            arg_group="Properties",
            help="Whether to enable certificate name check at origin level",
            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 Front Door 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.shared_private_link_resource = AAZObjectArg(
            options=["--shared-private-link-resource"],
            arg_group="Properties",
            help="The properties of the private link resource for private origin.",
            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,
            ),
        )

        shared_private_link_resource = cls._args_schema.shared_private_link_resource
        shared_private_link_resource.group_id = AAZStrArg(
            options=["group-id"],
            help="The group id from the provider of resource the shared private link resource is for.",
            nullable=True,
        )
        shared_private_link_resource.private_link = AAZObjectArg(
            options=["private-link"],
            help="The resource id of the resource the shared private link resource is for.",
            nullable=True,
        )
        cls._build_args_resource_reference_update(shared_private_link_resource.private_link)
        shared_private_link_resource.private_link_location = AAZStrArg(
            options=["private-link-location"],
            help="The location of the shared private link resource",
            nullable=True,
        )
        shared_private_link_resource.request_message = AAZStrArg(
            options=["request-message"],
            help="The request message for requesting approval of the shared private link resource.",
            nullable=True,
        )
        shared_private_link_resource.status = AAZStrArg(
            options=["status"],
            help="Status of the shared private link resource. Can be Pending, Approved, Rejected, Disconnected, or Timeout.",
            nullable=True,
            enum={"Approved": "Approved", "Disconnected": "Disconnected", "Pending": "Pending", "Rejected": "Rejected", "Timeout": "Timeout"},
        )
        return cls._args_schema

    _args_resource_reference_update = None

    @classmethod
    def _build_args_resource_reference_update(cls, _schema):
        if cls._args_resource_reference_update is not None:
            _schema.id = cls._args_resource_reference_update.id
            return

        cls._args_resource_reference_update = AAZObjectArg(
            nullable=True,
        )

        resource_reference_update = cls._args_resource_reference_update
        resource_reference_update.id = AAZStrArg(
            options=["id"],
            help="Resource ID.",
            nullable=True,
        )

        _schema.id = cls._args_resource_reference_update.id

    def _execute_operations(self):
        self.pre_operations()
        self.AFDOriginsGet(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.AFDOriginsCreate(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 AFDOriginsGet(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}/originGroups/{originGroupName}/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(
                    "originGroupName", self.ctx.args.origin_group_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", "2025-06-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_afd_origin_read(cls._schema_on_200)

            return cls._schema_on_200

    class AFDOriginsCreate(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}/originGroups/{originGroupName}/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(
                    "originGroupName", self.ctx.args.origin_group_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", "2025-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,
                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_afd_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("enabledState", AAZStrType, ".enabled_state")
                properties.set_prop("enforceCertificateNameCheck", AAZBoolType, ".enforce_certificate_name_check")
                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("sharedPrivateLinkResource", AAZObjectType, ".shared_private_link_resource")
                properties.set_prop("weight", AAZIntType, ".weight")

            shared_private_link_resource = _builder.get(".properties.sharedPrivateLinkResource")
            if shared_private_link_resource is not None:
                shared_private_link_resource.set_prop("groupId", AAZStrType, ".group_id")
                _UpdateHelper._build_schema_resource_reference_update(shared_private_link_resource.set_prop("privateLink", AAZObjectType, ".private_link"))
                shared_private_link_resource.set_prop("privateLinkLocation", AAZStrType, ".private_link_location")
                shared_private_link_resource.set_prop("requestMessage", AAZStrType, ".request_message")
                shared_private_link_resource.set_prop("status", AAZStrType, ".status")

            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_resource_reference_update(cls, _builder):
        if _builder is None:
            return
        _builder.set_prop("id", AAZStrType, ".id")

    _schema_afd_origin_read = None

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

        cls._schema_afd_origin_read = _schema_afd_origin_read = AAZObjectType()

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

        properties = _schema_afd_origin_read.properties
        properties.azure_origin = AAZObjectType(
            serialized_name="azureOrigin",
        )
        cls._build_schema_resource_reference_read(properties.azure_origin)
        properties.deployment_status = AAZStrType(
            serialized_name="deploymentStatus",
            flags={"read_only": True},
        )
        properties.enabled_state = AAZStrType(
            serialized_name="enabledState",
        )
        properties.enforce_certificate_name_check = AAZBoolType(
            serialized_name="enforceCertificateNameCheck",
        )
        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_group_name = AAZStrType(
            serialized_name="originGroupName",
            flags={"read_only": True},
        )
        properties.origin_host_header = AAZStrType(
            serialized_name="originHostHeader",
        )
        properties.priority = AAZIntType()
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.shared_private_link_resource = AAZObjectType(
            serialized_name="sharedPrivateLinkResource",
        )
        properties.weight = AAZIntType()

        shared_private_link_resource = _schema_afd_origin_read.properties.shared_private_link_resource
        shared_private_link_resource.group_id = AAZStrType(
            serialized_name="groupId",
        )
        shared_private_link_resource.private_link = AAZObjectType(
            serialized_name="privateLink",
        )
        cls._build_schema_resource_reference_read(shared_private_link_resource.private_link)
        shared_private_link_resource.private_link_location = AAZStrType(
            serialized_name="privateLinkLocation",
        )
        shared_private_link_resource.request_message = AAZStrType(
            serialized_name="requestMessage",
        )
        shared_private_link_resource.status = AAZStrType()

        system_data = _schema_afd_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_afd_origin_read.id
        _schema.name = cls._schema_afd_origin_read.name
        _schema.properties = cls._schema_afd_origin_read.properties
        _schema.system_data = cls._schema_afd_origin_read.system_data
        _schema.type = cls._schema_afd_origin_read.type

    _schema_resource_reference_read = None

    @classmethod
    def _build_schema_resource_reference_read(cls, _schema):
        if cls._schema_resource_reference_read is not None:
            _schema.id = cls._schema_resource_reference_read.id
            return

        cls._schema_resource_reference_read = _schema_resource_reference_read = AAZObjectType()

        resource_reference_read = _schema_resource_reference_read
        resource_reference_read.id = AAZStrType()

        _schema.id = cls._schema_resource_reference_read.id


__all__ = ["Update"]
