# --------------------------------------------------------------------------------------------
# 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(
    "monitor metrics alert update",
)
class Update(AAZCommand):
    """Update a metric-based alert rule.

    :example: Disable/Enable a metric-based alert rule.
        az monitor metrics alert update --enabled false --name MyAlertRule --resource-group MyResourceGroup
    """

    _aaz_info = {
        "version": "2018-03-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/metricalerts/{}", "2018-03-01"],
        ]
    }

    AZ_SUPPORT_GENERIC_UPDATE = True

    def _handler(self, command_args):
        super()._handler(command_args)
        self._execute_operations()
        return 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.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="Name of the alert rule.",
            required=True,
            id_part="name",
        )
        _args_schema.auto_mitigate = AAZBoolArg(
            options=["--auto-mitigate"],
            help="Automatically resolve the alert.",
            nullable=True,
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            help="Free-text description of the rule.",
            nullable=True,
        )
        _args_schema.enabled = AAZBoolArg(
            options=["--enabled"],
            help="Whether the metric alert rule is enabled.",
        )
        _args_schema.evaluation_frequency = AAZDurationArg(
            options=["--evaluation-frequency"],
            help="Frequency with which to evaluate the rule in `##h##m##s` format.",
        )
        _args_schema.scopes = AAZListArg(
            options=["--scopes"],
            help="Space-separated list of scopes the rule applies to. The resources specified in this parameter must be of the same type and exist in the same location.",
        )
        _args_schema.severity = AAZIntArg(
            options=["--severity"],
            help="Severity of the alert from 0 (critical) to 4 (verbose).",
        )
        _args_schema.window_size = AAZDurationArg(
            options=["--window-size"],
            help="Time over which to aggregate metrics in `##h##m##s` format.",
        )
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            help="Space-separated tags: key[=value] [key[=value] ...].",
            nullable=True,
        )

        scopes = cls._args_schema.scopes
        scopes.Element = AAZStrArg(
            nullable=True,
        )

        tags = cls._args_schema.tags
        tags.Element = AAZStrArg(
            nullable=True,
        )

        # define Arg Group "Properties"
        return cls._args_schema

    _args_metric_dimension_update = None

    @classmethod
    def _build_args_metric_dimension_update(cls, _schema):
        if cls._args_metric_dimension_update is not None:
            _schema.name = cls._args_metric_dimension_update.name
            _schema.operator = cls._args_metric_dimension_update.operator
            _schema.values = cls._args_metric_dimension_update.values
            return

        cls._args_metric_dimension_update = AAZObjectArg(
            nullable=True,
        )

        metric_dimension_update = cls._args_metric_dimension_update
        metric_dimension_update.name = AAZStrArg(
            options=["name"],
            help="Name of the dimension.",
        )
        metric_dimension_update.operator = AAZStrArg(
            options=["operator"],
            help="the dimension operator. Only 'Include' and 'Exclude' are supported",
        )
        metric_dimension_update.values = AAZListArg(
            options=["values"],
            help="list of dimension values.",
        )

        values = cls._args_metric_dimension_update.values
        values.Element = AAZStrArg(
            nullable=True,
        )

        _schema.name = cls._args_metric_dimension_update.name
        _schema.operator = cls._args_metric_dimension_update.operator
        _schema.values = cls._args_metric_dimension_update.values

    def _execute_operations(self):
        self.pre_operations()
        self.MetricAlertsGet(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)
        self.MetricAlertsCreateOrUpdate(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 MetricAlertsGet(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.Insights/metricAlerts/{ruleName}",
                **self.url_parameters
            )

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

        @property
        def error_format(self):
            return "ODataV4Format"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "ruleName", self.ctx.args.name,
                    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", "2018-03-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_metric_alert_resource_read(cls._schema_on_200)

            return cls._schema_on_200

    class MetricAlertsCreateOrUpdate(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.Insights/metricAlerts/{ruleName}",
                **self.url_parameters
            )

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

        @property
        def error_format(self):
            return "ODataV4Format"

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "ruleName", self.ctx.args.name,
                    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", "2018-03-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(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_metric_alert_resource_read(cls._schema_on_200)

            return cls._schema_on_200

    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": {"required": True, "client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("autoMitigate", AAZBoolType, ".auto_mitigate")
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("enabled", AAZBoolType, ".enabled", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("evaluationFrequency", AAZStrType, ".evaluation_frequency", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("severity", AAZIntType, ".severity", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("windowSize", AAZStrType, ".window_size", typ_kwargs={"flags": {"required": True}})

            scopes = _builder.get(".properties.scopes")
            if scopes is not None:
                scopes.set_elements(AAZStrType, ".")

            tags = _builder.get(".tags")
            if tags is not None:
                tags.set_elements(AAZStrType, ".")

            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_metric_dimension_update(cls, _builder):
        if _builder is None:
            return
        _builder.set_prop("name", AAZStrType, ".name", typ_kwargs={"flags": {"required": True}})
        _builder.set_prop("operator", AAZStrType, ".operator", typ_kwargs={"flags": {"required": True}})
        _builder.set_prop("values", AAZListType, ".values", typ_kwargs={"flags": {"required": True}})

        values = _builder.get(".values")
        if values is not None:
            values.set_elements(AAZStrType, ".")

    _schema_metric_alert_resource_read = None

    @classmethod
    def _build_schema_metric_alert_resource_read(cls, _schema):
        if cls._schema_metric_alert_resource_read is not None:
            _schema.id = cls._schema_metric_alert_resource_read.id
            _schema.location = cls._schema_metric_alert_resource_read.location
            _schema.name = cls._schema_metric_alert_resource_read.name
            _schema.properties = cls._schema_metric_alert_resource_read.properties
            _schema.tags = cls._schema_metric_alert_resource_read.tags
            _schema.type = cls._schema_metric_alert_resource_read.type
            return

        cls._schema_metric_alert_resource_read = _schema_metric_alert_resource_read = AAZObjectType()

        metric_alert_resource_read = _schema_metric_alert_resource_read
        metric_alert_resource_read.id = AAZStrType(
            flags={"read_only": True},
        )
        metric_alert_resource_read.location = AAZStrType(
            flags={"required": True},
        )
        metric_alert_resource_read.name = AAZStrType(
            flags={"read_only": True},
        )
        metric_alert_resource_read.properties = AAZObjectType(
            flags={"required": True, "client_flatten": True},
        )
        metric_alert_resource_read.tags = AAZDictType()
        metric_alert_resource_read.type = AAZStrType(
            flags={"read_only": True},
        )

        properties = _schema_metric_alert_resource_read.properties
        properties.actions = AAZListType()
        properties.auto_mitigate = AAZBoolType(
            serialized_name="autoMitigate",
        )
        properties.criteria = AAZObjectType(
            flags={"required": True},
        )
        properties.description = AAZStrType()
        properties.enabled = AAZBoolType(
            flags={"required": True},
        )
        properties.evaluation_frequency = AAZStrType(
            serialized_name="evaluationFrequency",
            flags={"required": True},
        )
        properties.is_migrated = AAZBoolType(
            serialized_name="isMigrated",
            flags={"read_only": True},
        )
        properties.last_updated_time = AAZStrType(
            serialized_name="lastUpdatedTime",
            flags={"read_only": True},
        )
        properties.scopes = AAZListType(
            flags={"required": True},
        )
        properties.severity = AAZIntType(
            flags={"required": True},
        )
        properties.target_resource_region = AAZStrType(
            serialized_name="targetResourceRegion",
        )
        properties.target_resource_type = AAZStrType(
            serialized_name="targetResourceType",
        )
        properties.window_size = AAZStrType(
            serialized_name="windowSize",
            flags={"required": True},
        )

        actions = _schema_metric_alert_resource_read.properties.actions
        actions.Element = AAZObjectType()

        _element = _schema_metric_alert_resource_read.properties.actions.Element
        _element.action_group_id = AAZStrType(
            serialized_name="actionGroupId",
        )
        _element.web_hook_properties = AAZDictType(
            serialized_name="webHookProperties",
        )

        web_hook_properties = _schema_metric_alert_resource_read.properties.actions.Element.web_hook_properties
        web_hook_properties.Element = AAZStrType()

        criteria = _schema_metric_alert_resource_read.properties.criteria
        criteria["odata.type"] = AAZStrType(
            flags={"required": True},
        )

        disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria")
        disc_microsoft__azure__monitor__multiple_resource_multiple_metric_criteria.all_of = AAZListType(
            serialized_name="allOf",
        )

        all_of = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of
        all_of.Element = AAZObjectType()

        _element = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element
        _element.criterion_type = AAZStrType(
            serialized_name="criterionType",
            flags={"required": True},
        )
        _element.dimensions = AAZListType()
        _element.metric_name = AAZStrType(
            serialized_name="metricName",
            flags={"required": True},
        )
        _element.metric_namespace = AAZStrType(
            serialized_name="metricNamespace",
        )
        _element.name = AAZStrType(
            flags={"required": True},
        )
        _element.skip_metric_validation = AAZBoolType(
            serialized_name="skipMetricValidation",
        )
        _element.time_aggregation = AAZStrType(
            serialized_name="timeAggregation",
            flags={"required": True},
        )

        dimensions = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.dimensions
        dimensions.Element = AAZObjectType()
        cls._build_schema_metric_dimension_read(dimensions.Element)

        disc_dynamic_threshold_criterion = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion")
        disc_dynamic_threshold_criterion.alert_sensitivity = AAZStrType(
            serialized_name="alertSensitivity",
            flags={"required": True},
        )
        disc_dynamic_threshold_criterion.failing_periods = AAZObjectType(
            serialized_name="failingPeriods",
            flags={"required": True},
        )
        disc_dynamic_threshold_criterion.ignore_data_before = AAZStrType(
            serialized_name="ignoreDataBefore",
        )
        disc_dynamic_threshold_criterion.operator = AAZStrType(
            flags={"required": True},
        )

        failing_periods = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "DynamicThresholdCriterion").failing_periods
        failing_periods.min_failing_periods_to_alert = AAZFloatType(
            serialized_name="minFailingPeriodsToAlert",
            flags={"required": True},
        )
        failing_periods.number_of_evaluation_periods = AAZFloatType(
            serialized_name="numberOfEvaluationPeriods",
            flags={"required": True},
        )

        disc_static_threshold_criterion = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria").all_of.Element.discriminate_by("criterion_type", "StaticThresholdCriterion")
        disc_static_threshold_criterion.operator = AAZStrType(
            flags={"required": True},
        )
        disc_static_threshold_criterion.threshold = AAZFloatType(
            flags={"required": True},
        )

        disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria")
        disc_microsoft__azure__monitor__single_resource_multiple_metric_criteria.all_of = AAZListType(
            serialized_name="allOf",
        )

        all_of = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of
        all_of.Element = AAZObjectType()

        _element = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element
        _element.criterion_type = AAZStrType(
            serialized_name="criterionType",
            flags={"required": True},
        )
        _element.dimensions = AAZListType()
        _element.metric_name = AAZStrType(
            serialized_name="metricName",
            flags={"required": True},
        )
        _element.metric_namespace = AAZStrType(
            serialized_name="metricNamespace",
        )
        _element.name = AAZStrType(
            flags={"required": True},
        )
        _element.operator = AAZStrType(
            flags={"required": True},
        )
        _element.skip_metric_validation = AAZBoolType(
            serialized_name="skipMetricValidation",
        )
        _element.threshold = AAZFloatType(
            flags={"required": True},
        )
        _element.time_aggregation = AAZStrType(
            serialized_name="timeAggregation",
            flags={"required": True},
        )

        dimensions = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria").all_of.Element.dimensions
        dimensions.Element = AAZObjectType()
        cls._build_schema_metric_dimension_read(dimensions.Element)

        disc_microsoft__azure__monitor__webtest_location_availability_criteria = _schema_metric_alert_resource_read.properties.criteria.discriminate_by("odata.type", "Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria")
        disc_microsoft__azure__monitor__webtest_location_availability_criteria.component_id = AAZStrType(
            serialized_name="componentId",
            flags={"required": True},
        )
        disc_microsoft__azure__monitor__webtest_location_availability_criteria.failed_location_count = AAZFloatType(
            serialized_name="failedLocationCount",
            flags={"required": True},
        )
        disc_microsoft__azure__monitor__webtest_location_availability_criteria.web_test_id = AAZStrType(
            serialized_name="webTestId",
            flags={"required": True},
        )

        scopes = _schema_metric_alert_resource_read.properties.scopes
        scopes.Element = AAZStrType()

        tags = _schema_metric_alert_resource_read.tags
        tags.Element = AAZStrType()

        _schema.id = cls._schema_metric_alert_resource_read.id
        _schema.location = cls._schema_metric_alert_resource_read.location
        _schema.name = cls._schema_metric_alert_resource_read.name
        _schema.properties = cls._schema_metric_alert_resource_read.properties
        _schema.tags = cls._schema_metric_alert_resource_read.tags
        _schema.type = cls._schema_metric_alert_resource_read.type

    _schema_metric_dimension_read = None

    @classmethod
    def _build_schema_metric_dimension_read(cls, _schema):
        if cls._schema_metric_dimension_read is not None:
            _schema.name = cls._schema_metric_dimension_read.name
            _schema.operator = cls._schema_metric_dimension_read.operator
            _schema.values = cls._schema_metric_dimension_read.values
            return

        cls._schema_metric_dimension_read = _schema_metric_dimension_read = AAZObjectType()

        metric_dimension_read = _schema_metric_dimension_read
        metric_dimension_read.name = AAZStrType(
            flags={"required": True},
        )
        metric_dimension_read.operator = AAZStrType(
            flags={"required": True},
        )
        metric_dimension_read.values = AAZListType(
            flags={"required": True},
        )

        values = _schema_metric_dimension_read.values
        values.Element = AAZStrType()

        _schema.name = cls._schema_metric_dimension_read.name
        _schema.operator = cls._schema_metric_dimension_read.operator
        _schema.values = cls._schema_metric_dimension_read.values


__all__ = ["Update"]
