# --------------------------------------------------------------------------------------------
# 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(
    "sentinel entity-query create",
    is_experimental=True,
)
class Create(AAZCommand):
    """Create the entity query.
    """

    _aaz_info = {
        "version": "2022-06-01-preview",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/providers/microsoft.securityinsights/entityqueries/{}", "2022-06-01-preview"],
        ]
    }

    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.entity_query_id = AAZStrArg(
            options=["-n", "--name", "--entity-query-id"],
            help="entity query ID",
            required=True,
            id_part="child_name_1",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.workspace_name = AAZStrArg(
            options=["-w", "--workspace-name"],
            help="The name of the workspace.",
            required=True,
            is_experimental=True,
            id_part="name",
        )

        # define Arg Group "EntityQuery"

        _args_schema = cls._args_schema
        _args_schema.activity = AAZObjectArg(
            options=["--activity"],
            arg_group="EntityQuery",
        )
        _args_schema.etag = AAZStrArg(
            options=["--etag"],
            arg_group="EntityQuery",
            help="Etag of the azure resource",
        )

        activity = cls._args_schema.activity
        activity.content = AAZStrArg(
            options=["content"],
            help="The entity query content to display in timeline",
        )
        activity.description = AAZStrArg(
            options=["description"],
            help="The entity query description",
        )
        activity.enabled = AAZBoolArg(
            options=["enabled"],
            help="Determines whether this activity is enabled or disabled.",
        )
        activity.entities_filter = AAZDictArg(
            options=["entities-filter"],
            help="The query applied only to entities matching to all filters",
        )
        activity.input_entity_type = AAZStrArg(
            options=["input-entity-type"],
            help="The type of the query's source entity",
            enum={"Account": "Account", "AzureResource": "AzureResource", "CloudApplication": "CloudApplication", "DNS": "DNS", "File": "File", "FileHash": "FileHash", "Host": "Host", "HuntingBookmark": "HuntingBookmark", "IP": "IP", "IoTDevice": "IoTDevice", "MailCluster": "MailCluster", "MailMessage": "MailMessage", "Mailbox": "Mailbox", "Malware": "Malware", "Process": "Process", "RegistryKey": "RegistryKey", "RegistryValue": "RegistryValue", "SecurityAlert": "SecurityAlert", "SecurityGroup": "SecurityGroup", "SubmissionMail": "SubmissionMail", "URL": "URL"},
        )
        activity.query_definitions = AAZObjectArg(
            options=["query-definitions"],
            help="The Activity query definitions",
        )
        activity.required_input_fields_sets = AAZListArg(
            options=["required-input-fields-sets"],
            help="List of the fields of the source entity that are required to run the query",
        )
        activity.template_name = AAZStrArg(
            options=["template-name"],
            help="The template id this activity was created from",
        )
        activity.title = AAZStrArg(
            options=["title"],
            help="The entity query title",
        )

        entities_filter = cls._args_schema.activity.entities_filter
        entities_filter.Element = AAZListArg()

        _element = cls._args_schema.activity.entities_filter.Element
        _element.Element = AAZStrArg()

        query_definitions = cls._args_schema.activity.query_definitions
        query_definitions.query = AAZStrArg(
            options=["query"],
            help="The Activity query to run on a given entity",
        )

        required_input_fields_sets = cls._args_schema.activity.required_input_fields_sets
        required_input_fields_sets.Element = AAZListArg()

        _element = cls._args_schema.activity.required_input_fields_sets.Element
        _element.Element = AAZStrArg()
        return cls._args_schema

    def _execute_operations(self):
        self.EntityQueriesCreateOrUpdate(ctx=self.ctx)()

    def _output(self, *args, **kwargs):
        result = self.deserialize_output(self.ctx.vars.instance, client_flatten=True)
        return result

    class EntityQueriesCreateOrUpdate(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.OperationalInsights/workspaces/{workspaceName}/providers/Microsoft.SecurityInsights/entityQueries/{entityQueryId}",
                **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(
                    "entityQueryId", self.ctx.args.entity_query_id,
                    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,
                ),
                **self.serialize_url_param(
                    "workspaceName", self.ctx.args.workspace_name,
                    required=True,
                ),
            }
            return parameters

        @property
        def query_parameters(self):
            parameters = {
                **self.serialize_query_param(
                    "api-version", "2022-06-01-preview",
                    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("etag", AAZStrType, ".etag")
            _builder.set_const("kind", "Activity", AAZStrType, ".activity", typ_kwargs={"flags": {"required": True}})
            _builder.discriminate_by("kind", "Activity")

            disc_activity = _builder.get("{kind:Activity}")
            if disc_activity is not None:
                disc_activity.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get("{kind:Activity}.properties")
            if properties is not None:
                properties.set_prop("content", AAZStrType, ".activity.content")
                properties.set_prop("description", AAZStrType, ".activity.description")
                properties.set_prop("enabled", AAZBoolType, ".activity.enabled")
                properties.set_prop("entitiesFilter", AAZDictType, ".activity.entities_filter")
                properties.set_prop("inputEntityType", AAZStrType, ".activity.input_entity_type")
                properties.set_prop("queryDefinitions", AAZObjectType, ".activity.query_definitions")
                properties.set_prop("requiredInputFieldsSets", AAZListType, ".activity.required_input_fields_sets")
                properties.set_prop("templateName", AAZStrType, ".activity.template_name")
                properties.set_prop("title", AAZStrType, ".activity.title")

            entities_filter = _builder.get("{kind:Activity}.properties.entitiesFilter")
            if entities_filter is not None:
                entities_filter.set_elements(AAZListType)

            _elements = _builder.get("{kind:Activity}.properties.entitiesFilter{}")
            if _elements is not None:
                _elements.set_elements(AAZStrType, ".")

            query_definitions = _builder.get("{kind:Activity}.properties.queryDefinitions")
            if query_definitions is not None:
                query_definitions.set_prop("query", AAZStrType, ".query")

            required_input_fields_sets = _builder.get("{kind:Activity}.properties.requiredInputFieldsSets")
            if required_input_fields_sets is not None:
                required_input_fields_sets.set_elements(AAZListType)

            _elements = _builder.get("{kind:Activity}.properties.requiredInputFieldsSets[]")
            if _elements is not None:
                _elements.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.etag = AAZStrType()
            _schema_on_200_201.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.kind = AAZStrType(
                flags={"required": True},
            )
            _schema_on_200_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.system_data = AAZObjectType(
                serialized_name="systemData",
                flags={"read_only": True},
            )
            _schema_on_200_201.type = AAZStrType(
                flags={"read_only": True},
            )

            system_data = cls._schema_on_200_201.system_data
            system_data.created_at = AAZStrType(
                serialized_name="createdAt",
                flags={"read_only": True},
            )
            system_data.created_by = AAZStrType(
                serialized_name="createdBy",
                flags={"read_only": True},
            )
            system_data.created_by_type = AAZStrType(
                serialized_name="createdByType",
                flags={"read_only": True},
            )
            system_data.last_modified_at = AAZStrType(
                serialized_name="lastModifiedAt",
                flags={"read_only": True},
            )
            system_data.last_modified_by = AAZStrType(
                serialized_name="lastModifiedBy",
                flags={"read_only": True},
            )
            system_data.last_modified_by_type = AAZStrType(
                serialized_name="lastModifiedByType",
                flags={"read_only": True},
            )

            disc_activity = cls._schema_on_200_201.discriminate_by("kind", "Activity")
            disc_activity.properties = AAZObjectType(
                flags={"client_flatten": True},
            )

            properties = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties
            properties.content = AAZStrType()
            properties.created_time_utc = AAZStrType(
                serialized_name="createdTimeUtc",
                flags={"read_only": True},
            )
            properties.description = AAZStrType()
            properties.enabled = AAZBoolType()
            properties.entities_filter = AAZDictType(
                serialized_name="entitiesFilter",
            )
            properties.input_entity_type = AAZStrType(
                serialized_name="inputEntityType",
            )
            properties.last_modified_time_utc = AAZStrType(
                serialized_name="lastModifiedTimeUtc",
                flags={"read_only": True},
            )
            properties.query_definitions = AAZObjectType(
                serialized_name="queryDefinitions",
            )
            properties.required_input_fields_sets = AAZListType(
                serialized_name="requiredInputFieldsSets",
            )
            properties.template_name = AAZStrType(
                serialized_name="templateName",
            )
            properties.title = AAZStrType()

            entities_filter = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties.entities_filter
            entities_filter.Element = AAZListType()

            _element = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties.entities_filter.Element
            _element.Element = AAZStrType()

            query_definitions = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties.query_definitions
            query_definitions.query = AAZStrType()

            required_input_fields_sets = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties.required_input_fields_sets
            required_input_fields_sets.Element = AAZListType()

            _element = cls._schema_on_200_201.discriminate_by("kind", "Activity").properties.required_input_fields_sets.Element
            _element.Element = AAZStrType()

            disc_expansion = cls._schema_on_200_201.discriminate_by("kind", "Expansion")
            disc_expansion.properties = AAZObjectType(
                flags={"client_flatten": True},
            )

            properties = cls._schema_on_200_201.discriminate_by("kind", "Expansion").properties
            properties.data_sources = AAZListType(
                serialized_name="dataSources",
            )
            properties.display_name = AAZStrType(
                serialized_name="displayName",
            )
            properties.input_entity_type = AAZStrType(
                serialized_name="inputEntityType",
            )
            properties.input_fields = AAZListType(
                serialized_name="inputFields",
            )
            properties.output_entity_types = AAZListType(
                serialized_name="outputEntityTypes",
            )
            properties.query_template = AAZStrType(
                serialized_name="queryTemplate",
            )

            data_sources = cls._schema_on_200_201.discriminate_by("kind", "Expansion").properties.data_sources
            data_sources.Element = AAZStrType()

            input_fields = cls._schema_on_200_201.discriminate_by("kind", "Expansion").properties.input_fields
            input_fields.Element = AAZStrType()

            output_entity_types = cls._schema_on_200_201.discriminate_by("kind", "Expansion").properties.output_entity_types
            output_entity_types.Element = AAZStrType()

            return cls._schema_on_200_201


__all__ = ["Create"]
