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

    :example: Create an origin group
        az cdn origin-group create -g group --profile-name profile --endpoint-name endpoint -n origin-group --origins origin-0,origin-1

    :example: Create an origin group with a custom health probe
        az cdn origin-group create -g group --profile-name profile --endpoint-name endpoint -n origin-group --origins origin-0,origin-1 --probe-path /healthz --probe-interval 90 --probe-protocol HTTPS --probe-method GET
    """

    _aaz_info = {
        "version": "2023-05-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.cdn/profiles/{}/endpoints/{}/origingroups/{}", "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_group_name = AAZStrArg(
            options=["-n", "--name", "--origin-group-name"],
            help="Name of the origin group which 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.health_probe_settings = AAZObjectArg(
            options=["--health-probe-settings"],
            arg_group="Properties",
            help="Health probe settings to the origin that is used to determine the health of the origin.",
        )
        _args_schema.formatted_origins = AAZListArg(
            options=["--formatted-origins"],
            arg_group="Properties",
            help="The source of the content being delivered via CDN within given origin group.",
        )
        _args_schema.response_based_origin_error_detection_settings = AAZObjectArg(
            options=["--response-based-origin-error-detection-settings"],
            arg_group="Properties",
            help="The JSON object that contains the properties to determine origin health using real requests/responses. This property is currently not supported.",
        )
        _args_schema.traffic_restoration_time_to_healed_or_new_endpoints_in_minutes = AAZIntArg(
            options=["--traffic-restoration-time-to-healed-or-new-endpoints-in-minutes"],
            arg_group="Properties",
            help="Time in minutes to shift the traffic to the endpoint gradually when an unhealthy endpoint comes healthy or a new endpoint is added. Default is 10 mins. This property is currently not supported.",
            fmt=AAZIntArgFormat(
                maximum=50,
                minimum=0,
            ),
        )

        health_probe_settings = cls._args_schema.health_probe_settings
        health_probe_settings.probe_interval_in_seconds = AAZIntArg(
            options=["probe-interval-in-seconds"],
            help="The number of seconds between health probes.Default is 240sec.",
            fmt=AAZIntArgFormat(
                maximum=255,
                minimum=1,
            ),
        )
        health_probe_settings.probe_path = AAZStrArg(
            options=["probe-path"],
            help="The path relative to the origin that is used to determine the health of the origin.",
        )
        health_probe_settings.probe_protocol = AAZStrArg(
            options=["probe-protocol"],
            help="Protocol to use for health probe.",
            enum={"Http": "Http", "Https": "Https", "NotSet": "NotSet"},
        )
        health_probe_settings.probe_request_type = AAZStrArg(
            options=["probe-request-type"],
            help="The type of health probe request that is made.",
            enum={"GET": "GET", "HEAD": "HEAD", "NotSet": "NotSet"},
        )

        formatted_origins = cls._args_schema.formatted_origins
        formatted_origins.Element = AAZObjectArg()

        _element = cls._args_schema.formatted_origins.Element
        _element.id = AAZStrArg(
            options=["id"],
            help="Resource ID.",
        )

        response_based_origin_error_detection_settings = cls._args_schema.response_based_origin_error_detection_settings
        response_based_origin_error_detection_settings.http_error_ranges = AAZListArg(
            options=["http-error-ranges"],
            help="The list of Http status code ranges that are considered as server errors for origin and it is marked as unhealthy.",
        )
        response_based_origin_error_detection_settings.response_based_detected_error_types = AAZStrArg(
            options=["response-based-detected-error-types"],
            help="Type of response errors for real user requests for which origin will be deemed unhealthy",
            enum={"None": "None", "TcpAndHttpErrors": "TcpAndHttpErrors", "TcpErrorsOnly": "TcpErrorsOnly"},
        )
        response_based_origin_error_detection_settings.response_based_failover_threshold_percentage = AAZIntArg(
            options=["response-based-failover-threshold-percentage"],
            help="The percentage of failed requests in the sample where failover should trigger.",
            fmt=AAZIntArgFormat(
                maximum=100,
                minimum=0,
            ),
        )

        http_error_ranges = cls._args_schema.response_based_origin_error_detection_settings.http_error_ranges
        http_error_ranges.Element = AAZObjectArg()

        _element = cls._args_schema.response_based_origin_error_detection_settings.http_error_ranges.Element
        _element.begin = AAZIntArg(
            options=["begin"],
            help="The inclusive start of the http status code range.",
            fmt=AAZIntArgFormat(
                maximum=999,
                minimum=100,
            ),
        )
        _element.end = AAZIntArg(
            options=["end"],
            help="The inclusive end of the http status code range.",
            fmt=AAZIntArgFormat(
                maximum=999,
                minimum=100,
            ),
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.OriginGroupsCreate(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 OriginGroupsCreate(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}/originGroups/{originGroupName}",
                **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(
                    "originGroupName", self.ctx.args.origin_group_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("healthProbeSettings", AAZObjectType, ".health_probe_settings")
                properties.set_prop("origins", AAZListType, ".formatted_origins", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("responseBasedOriginErrorDetectionSettings", AAZObjectType, ".response_based_origin_error_detection_settings")
                properties.set_prop("trafficRestorationTimeToHealedOrNewEndpointsInMinutes", AAZIntType, ".traffic_restoration_time_to_healed_or_new_endpoints_in_minutes")

            health_probe_settings = _builder.get(".properties.healthProbeSettings")
            if health_probe_settings is not None:
                health_probe_settings.set_prop("probeIntervalInSeconds", AAZIntType, ".probe_interval_in_seconds")
                health_probe_settings.set_prop("probePath", AAZStrType, ".probe_path")
                health_probe_settings.set_prop("probeProtocol", AAZStrType, ".probe_protocol")
                health_probe_settings.set_prop("probeRequestType", AAZStrType, ".probe_request_type")

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

            _elements = _builder.get(".properties.origins[]")
            if _elements is not None:
                _elements.set_prop("id", AAZStrType, ".id")

            response_based_origin_error_detection_settings = _builder.get(".properties.responseBasedOriginErrorDetectionSettings")
            if response_based_origin_error_detection_settings is not None:
                response_based_origin_error_detection_settings.set_prop("httpErrorRanges", AAZListType, ".http_error_ranges")
                response_based_origin_error_detection_settings.set_prop("responseBasedDetectedErrorTypes", AAZStrType, ".response_based_detected_error_types")
                response_based_origin_error_detection_settings.set_prop("responseBasedFailoverThresholdPercentage", AAZIntType, ".response_based_failover_threshold_percentage")

            http_error_ranges = _builder.get(".properties.responseBasedOriginErrorDetectionSettings.httpErrorRanges")
            if http_error_ranges is not None:
                http_error_ranges.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.responseBasedOriginErrorDetectionSettings.httpErrorRanges[]")
            if _elements is not None:
                _elements.set_prop("begin", AAZIntType, ".begin")
                _elements.set_prop("end", AAZIntType, ".end")

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

            return cls._schema_on_200_201


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

    _schema_origin_group_read = None

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

        cls._schema_origin_group_read = _schema_origin_group_read = AAZObjectType()

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

        properties = _schema_origin_group_read.properties
        properties.health_probe_settings = AAZObjectType(
            serialized_name="healthProbeSettings",
        )
        properties.origins = AAZListType(
            flags={"required": True},
        )
        properties.provisioning_state = AAZStrType(
            serialized_name="provisioningState",
            flags={"read_only": True},
        )
        properties.resource_state = AAZStrType(
            serialized_name="resourceState",
            flags={"read_only": True},
        )
        properties.response_based_origin_error_detection_settings = AAZObjectType(
            serialized_name="responseBasedOriginErrorDetectionSettings",
        )
        properties.traffic_restoration_time_to_healed_or_new_endpoints_in_minutes = AAZIntType(
            serialized_name="trafficRestorationTimeToHealedOrNewEndpointsInMinutes",
        )

        health_probe_settings = _schema_origin_group_read.properties.health_probe_settings
        health_probe_settings.probe_interval_in_seconds = AAZIntType(
            serialized_name="probeIntervalInSeconds",
        )
        health_probe_settings.probe_path = AAZStrType(
            serialized_name="probePath",
        )
        health_probe_settings.probe_protocol = AAZStrType(
            serialized_name="probeProtocol",
        )
        health_probe_settings.probe_request_type = AAZStrType(
            serialized_name="probeRequestType",
        )

        origins = _schema_origin_group_read.properties.origins
        origins.Element = AAZObjectType()

        _element = _schema_origin_group_read.properties.origins.Element
        _element.id = AAZStrType()

        response_based_origin_error_detection_settings = _schema_origin_group_read.properties.response_based_origin_error_detection_settings
        response_based_origin_error_detection_settings.http_error_ranges = AAZListType(
            serialized_name="httpErrorRanges",
        )
        response_based_origin_error_detection_settings.response_based_detected_error_types = AAZStrType(
            serialized_name="responseBasedDetectedErrorTypes",
        )
        response_based_origin_error_detection_settings.response_based_failover_threshold_percentage = AAZIntType(
            serialized_name="responseBasedFailoverThresholdPercentage",
        )

        http_error_ranges = _schema_origin_group_read.properties.response_based_origin_error_detection_settings.http_error_ranges
        http_error_ranges.Element = AAZObjectType()

        _element = _schema_origin_group_read.properties.response_based_origin_error_detection_settings.http_error_ranges.Element
        _element.begin = AAZIntType()
        _element.end = AAZIntType()

        system_data = _schema_origin_group_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_group_read.id
        _schema.name = cls._schema_origin_group_read.name
        _schema.properties = cls._schema_origin_group_read.properties
        _schema.system_data = cls._schema_origin_group_read.system_data
        _schema.type = cls._schema_origin_group_read.type


__all__ = ["Create"]
