# --------------------------------------------------------------------------------------------
# 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 activity-log alert create",
)
class Create(AAZCommand):
    """Create a default activity log alert rule.

    This command will create a default activity log with one condition which compares if the activities logs 'category' field equals to 'ServiceHealth'. The newly created activity log alert does not have any action groups attached to it.

    :example: Create an alert rule with default settings.
        az monitor activity-log alert create -n AlertName -g ResourceGroup

    :example: Create an alert rule with condition about error level service health log.
        az monitor activity-log alert create -n AlertName -g ResourceGroup --condition category=ServiceHealth and level=Error

    :example: Create an alert rule with an action group and specify webhook properties.
        az monitor activity-log alert create -n AlertName -g ResourceGroup -a /subscriptions/{SubID}/resourceGroups/{ResourceGroup}/providers/microsoft.insights/actionGroups/{ActionGroup} -w usage=test owner=jane

    :example: Create an alert rule which is initially disabled.
        az monitor activity-log alert create -n AlertName -g ResourceGroup --disable
    """

    _aaz_info = {
        "version": "2020-10-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.insights/activitylogalerts/{}", "2020-10-01"],
        ]
    }

    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.activity_log_alert_name = AAZStrArg(
            options=["-n", "--name", "--activity-log-alert-name"],
            help="The name of the activity log alert.",
            required=True,
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.location = AAZResourceLocationArg(
            help="The location of the resource. Since Azure Activity Log Alerts is a global service, the location of the rules should always be 'global'.",
            default="global",
            fmt=AAZResourceLocationArgFormat(
                resource_group_arg="resource_group",
            ),
        )
        _args_schema.action_groups = AAZListArg(
            options=["--action-groups"],
            help="The list of the Action Groups.",
        )
        _args_schema.all_of = AAZListArg(
            options=["--all-of"],
            help="The list of Activity Log Alert rule conditions.",
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            help="A description of this Activity Log Alert rule.",
        )
        _args_schema.enabled = AAZBoolArg(
            options=["--enabled"],
            help="Indicates whether this Activity Log Alert rule is enabled. If an Activity Log Alert rule is not enabled, then none of its actions will be activated.",
            default=True,
        )
        _args_schema.scopes = AAZListArg(
            options=["--scopes"],
            help="A list of resource IDs that will be used as prefixes. The alert will only apply to Activity Log events with resource IDs that fall under one of these prefixes. This list must include at least one item.",
        )
        _args_schema.tags = AAZDictArg(
            options=["--tags"],
            help="The tags of the resource.",
        )

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

        _element = cls._args_schema.action_groups.Element
        _element.action_group_id = AAZStrArg(
            options=["action-group-id"],
            help="The resource ID of the Action Group. This cannot be null or empty.",
            required=True,
        )
        _element.webhook_properties = AAZDictArg(
            options=["webhook-properties"],
            help="the dictionary of custom properties to include with the post operation. These data are appended to the webhook payload.",
        )

        webhook_properties = cls._args_schema.action_groups.Element.webhook_properties
        webhook_properties.Element = AAZStrArg()

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

        _element = cls._args_schema.all_of.Element
        _element.any_of = AAZListArg(
            options=["any-of"],
            help="An Activity Log Alert rule condition that is met when at least one of its member leaf conditions are met.",
        )
        _element.contains_any = AAZListArg(
            options=["contains-any"],
            help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.",
        )
        _element.equals = AAZStrArg(
            options=["equals"],
            help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.",
        )
        _element.field = AAZStrArg(
            options=["field"],
            help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.",
        )

        any_of = cls._args_schema.all_of.Element.any_of
        any_of.Element = AAZObjectArg()

        _element = cls._args_schema.all_of.Element.any_of.Element
        _element.contains_any = AAZListArg(
            options=["contains-any"],
            help="The value of the event's field will be compared to the values in this array (case-insensitive) to determine if the condition is met.",
        )
        _element.equals = AAZStrArg(
            options=["equals"],
            help="The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.",
        )
        _element.field = AAZStrArg(
            options=["field"],
            help="The name of the Activity Log event's field that this condition will examine. The possible values for this field are (case-insensitive): 'resourceId', 'category', 'caller', 'level', 'operationName', 'resourceGroup', 'resourceProvider', 'status', 'subStatus', 'resourceType', or anything beginning with 'properties'.",
        )

        contains_any = cls._args_schema.all_of.Element.any_of.Element.contains_any
        contains_any.Element = AAZStrArg()

        contains_any = cls._args_schema.all_of.Element.contains_any
        contains_any.Element = AAZStrArg()

        scopes = cls._args_schema.scopes
        scopes.Element = AAZStrArg()

        tags = cls._args_schema.tags
        tags.Element = AAZStrArg()
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        self.ActivityLogAlertsCreateOrUpdate(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 ActivityLogAlertsCreateOrUpdate(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, 201]:
                return self.on_200_201(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/activityLogAlerts/{activityLogAlertName}",
                **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(
                    "activityLogAlertName", self.ctx.args.activity_log_alert_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", "2020-10-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("location", AAZStrType, ".location")
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})
            _builder.set_prop("tags", AAZDictType, ".tags")

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("actions", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("condition", AAZObjectType, ".", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("enabled", AAZBoolType, ".enabled")
                properties.set_prop("scopes", AAZListType, ".scopes", typ_kwargs={"flags": {"required": True}})

            actions = _builder.get(".properties.actions")
            if actions is not None:
                actions.set_prop("actionGroups", AAZListType, ".action_groups")

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

            _elements = _builder.get(".properties.actions.actionGroups[]")
            if _elements is not None:
                _elements.set_prop("actionGroupId", AAZStrType, ".action_group_id", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("webhookProperties", AAZDictType, ".webhook_properties")

            webhook_properties = _builder.get(".properties.actions.actionGroups[].webhookProperties")
            if webhook_properties is not None:
                webhook_properties.set_elements(AAZStrType, ".")

            condition = _builder.get(".properties.condition")
            if condition is not None:
                condition.set_prop("allOf", AAZListType, ".all_of", typ_kwargs={"flags": {"required": True}})

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

            _elements = _builder.get(".properties.condition.allOf[]")
            if _elements is not None:
                _elements.set_prop("anyOf", AAZListType, ".any_of")
                _elements.set_prop("containsAny", AAZListType, ".contains_any")
                _elements.set_prop("equals", AAZStrType, ".equals")
                _elements.set_prop("field", AAZStrType, ".field")

            any_of = _builder.get(".properties.condition.allOf[].anyOf")
            if any_of is not None:
                any_of.set_elements(AAZObjectType, ".")

            _elements = _builder.get(".properties.condition.allOf[].anyOf[]")
            if _elements is not None:
                _elements.set_prop("containsAny", AAZListType, ".contains_any")
                _elements.set_prop("equals", AAZStrType, ".equals")
                _elements.set_prop("field", AAZStrType, ".field")

            contains_any = _builder.get(".properties.condition.allOf[].anyOf[].containsAny")
            if contains_any is not None:
                contains_any.set_elements(AAZStrType, ".")

            contains_any = _builder.get(".properties.condition.allOf[].containsAny")
            if contains_any is not None:
                contains_any.set_elements(AAZStrType, ".")

            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 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()

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

            properties = cls._schema_on_200_201.properties
            properties.actions = AAZObjectType(
                flags={"required": True},
            )
            properties.condition = AAZObjectType(
                flags={"required": True},
            )
            properties.description = AAZStrType()
            properties.enabled = AAZBoolType()
            properties.scopes = AAZListType(
                flags={"required": True},
            )

            actions = cls._schema_on_200_201.properties.actions
            actions.action_groups = AAZListType(
                serialized_name="actionGroups",
            )

            action_groups = cls._schema_on_200_201.properties.actions.action_groups
            action_groups.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.actions.action_groups.Element
            _element.action_group_id = AAZStrType(
                serialized_name="actionGroupId",
                flags={"required": True},
            )
            _element.webhook_properties = AAZDictType(
                serialized_name="webhookProperties",
            )

            webhook_properties = cls._schema_on_200_201.properties.actions.action_groups.Element.webhook_properties
            webhook_properties.Element = AAZStrType()

            condition = cls._schema_on_200_201.properties.condition
            condition.all_of = AAZListType(
                serialized_name="allOf",
                flags={"required": True},
            )

            all_of = cls._schema_on_200_201.properties.condition.all_of
            all_of.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.condition.all_of.Element
            _element.any_of = AAZListType(
                serialized_name="anyOf",
            )
            _element.contains_any = AAZListType(
                serialized_name="containsAny",
            )
            _element.equals = AAZStrType()
            _element.field = AAZStrType()

            any_of = cls._schema_on_200_201.properties.condition.all_of.Element.any_of
            any_of.Element = AAZObjectType()

            _element = cls._schema_on_200_201.properties.condition.all_of.Element.any_of.Element
            _element.contains_any = AAZListType(
                serialized_name="containsAny",
            )
            _element.equals = AAZStrType()
            _element.field = AAZStrType()

            contains_any = cls._schema_on_200_201.properties.condition.all_of.Element.any_of.Element.contains_any
            contains_any.Element = AAZStrType()

            contains_any = cls._schema_on_200_201.properties.condition.all_of.Element.contains_any
            contains_any.Element = AAZStrType()

            scopes = cls._schema_on_200_201.properties.scopes
            scopes.Element = AAZStrType()

            tags = cls._schema_on_200_201.tags
            tags.Element = AAZStrType()

            return cls._schema_on_200_201


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


__all__ = ["Create"]
