# --------------------------------------------------------------------------------------------
# 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 watchlist create",
    is_experimental=True,
)
class Create(AAZCommand):
    """Create a Watchlist and its Watchlist Items (bulk creation, e.g. through text/csv content type). To create a Watchlist and its Items, we should call this endpoint with either rawContent or a valid SAR URI and contentType properties. The rawContent is mainly used for small watchlist (content size below 3.8 MB). The SAS URI enables the creation of large watchlist, where the content size can go up to 500 MB. The status of processing such large file can be polled through the URL returned in Azure-AsyncOperation header.
    """

    _aaz_info = {
        "version": "2022-06-01-preview",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.operationalinsights/workspaces/{}/providers/microsoft.securityinsights/watchlists/{}", "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.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.watchlist_alias = AAZStrArg(
            options=["-n", "--name", "--watchlist-alias"],
            help="Watchlist Alias",
            required=True,
            id_part="child_name_1",
        )
        _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 "Properties"

        _args_schema = cls._args_schema
        _args_schema.content_type = AAZStrArg(
            options=["--content-type"],
            arg_group="Properties",
            help="The content type of the raw content. Example : text/csv or text/tsv ",
        )
        _args_schema.created = AAZStrArg(
            options=["--created"],
            arg_group="Properties",
            help="The time the watchlist was created",
        )
        _args_schema.created_by = AAZObjectArg(
            options=["--created-by"],
            arg_group="Properties",
            help="Describes a user that created the watchlist",
        )
        cls._build_args_user_info_create(_args_schema.created_by)
        _args_schema.default_duration = AAZStrArg(
            options=["--default-duration"],
            arg_group="Properties",
            help="The default duration of a watchlist (in ISO 8601 duration format)",
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            arg_group="Properties",
            help="A description of the watchlist",
        )
        _args_schema.display_name = AAZStrArg(
            options=["--display-name"],
            arg_group="Properties",
            help="The display name of the watchlist",
        )
        _args_schema.is_deleted = AAZBoolArg(
            options=["--is-deleted"],
            arg_group="Properties",
            help="A flag that indicates if the watchlist is deleted or not",
        )
        _args_schema.items_search_key = AAZStrArg(
            options=["--items-search-key"],
            arg_group="Properties",
            help="The search key is used to optimize query performance when using watchlists for joins with other data. For example, enable a column with IP addresses to be the designated SearchKey field, then use this field as the key field when joining to other event data by IP address.",
        )
        _args_schema.labels = AAZListArg(
            options=["--labels"],
            arg_group="Properties",
            help="List of labels relevant to this watchlist",
        )
        _args_schema.skip_num = AAZIntArg(
            options=["--skip-num"],
            arg_group="Properties",
            help="The number of lines in a csv/tsv content to skip before the header",
        )
        _args_schema.provider = AAZStrArg(
            options=["--provider"],
            arg_group="Properties",
            help="The provider of the watchlist",
        )
        _args_schema.raw_content = AAZStrArg(
            options=["--raw-content"],
            arg_group="Properties",
            help="The raw content that represents to watchlist items to create. In case of csv/tsv content type, it's the content of the file that will parsed by the endpoint",
        )
        _args_schema.source = AAZStrArg(
            options=["--source"],
            arg_group="Properties",
            help="The filename of the watchlist, called 'source'",
        )
        _args_schema.source_type = AAZStrArg(
            options=["--source-type"],
            arg_group="Properties",
            help="The sourceType of the watchlist",
            enum={"Local file": "Local file", "Remote storage": "Remote storage"},
        )
        _args_schema.tenant_id = AAZStrArg(
            options=["--tenant-id"],
            arg_group="Properties",
            help="The tenantId where the watchlist belongs to",
        )
        _args_schema.updated = AAZStrArg(
            options=["--updated"],
            arg_group="Properties",
            help="The last time the watchlist was updated",
        )
        _args_schema.updated_by = AAZObjectArg(
            options=["--updated-by"],
            arg_group="Properties",
            help="Describes a user that updated the watchlist",
        )
        cls._build_args_user_info_create(_args_schema.updated_by)
        _args_schema.upload_status = AAZStrArg(
            options=["--upload-status"],
            arg_group="Properties",
            help="The status of the Watchlist upload : New, InProgress or Complete. Pls note : When a Watchlist upload status is equal to InProgress, the Watchlist cannot be deleted",
        )
        _args_schema.watchlist_id = AAZStrArg(
            options=["--watchlist-id"],
            arg_group="Properties",
            help="The id (a Guid) of the watchlist",
        )
        _args_schema.watchlist_type = AAZStrArg(
            options=["--watchlist-type"],
            arg_group="Properties",
            help="The type of the watchlist",
        )

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

        # define Arg Group "Watchlist"

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

    _args_user_info_create = None

    @classmethod
    def _build_args_user_info_create(cls, _schema):
        if cls._args_user_info_create is not None:
            _schema.object_id = cls._args_user_info_create.object_id
            return

        cls._args_user_info_create = AAZObjectArg()

        user_info_create = cls._args_user_info_create
        user_info_create.object_id = AAZStrArg(
            options=["object-id"],
            help="The object id of the user.",
            nullable=True,
        )

        _schema.object_id = cls._args_user_info_create.object_id

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

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

    class WatchlistsCreateOrUpdate(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/watchlists/{watchlistAlias}",
                **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(
                    "subscriptionId", self.ctx.subscription_id,
                    required=True,
                ),
                **self.serialize_url_param(
                    "watchlistAlias", self.ctx.args.watchlist_alias,
                    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_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("contentType", AAZStrType, ".content_type")
                properties.set_prop("created", AAZStrType, ".created")
                _build_schema_user_info_create(properties.set_prop("createdBy", AAZObjectType, ".created_by"))
                properties.set_prop("defaultDuration", AAZStrType, ".default_duration")
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("displayName", AAZStrType, ".display_name", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("isDeleted", AAZBoolType, ".is_deleted")
                properties.set_prop("itemsSearchKey", AAZStrType, ".items_search_key", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("labels", AAZListType, ".labels")
                properties.set_prop("numberOfLinesToSkip", AAZIntType, ".skip_num")
                properties.set_prop("provider", AAZStrType, ".provider", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("rawContent", AAZStrType, ".raw_content")
                properties.set_prop("source", AAZStrType, ".source")
                properties.set_prop("sourceType", AAZStrType, ".source_type")
                properties.set_prop("tenantId", AAZStrType, ".tenant_id")
                properties.set_prop("updated", AAZStrType, ".updated")
                _build_schema_user_info_create(properties.set_prop("updatedBy", AAZObjectType, ".updated_by"))
                properties.set_prop("uploadStatus", AAZStrType, ".upload_status")
                properties.set_prop("watchlistAlias", AAZStrType, ".watchlist_alias")
                properties.set_prop("watchlistId", AAZStrType, ".watchlist_id")
                properties.set_prop("watchlistType", AAZStrType, ".watchlist_type")

            labels = _builder.get(".properties.labels")
            if labels is not None:
                labels.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.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_200_201.properties = AAZObjectType(
                flags={"client_flatten": 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},
            )

            properties = cls._schema_on_200_201.properties
            properties.content_type = AAZStrType(
                serialized_name="contentType",
            )
            properties.created = AAZStrType()
            properties.created_by = AAZObjectType(
                serialized_name="createdBy",
            )
            _build_schema_user_info_read(properties.created_by)
            properties.default_duration = AAZStrType(
                serialized_name="defaultDuration",
            )
            properties.description = AAZStrType()
            properties.display_name = AAZStrType(
                serialized_name="displayName",
                flags={"required": True},
            )
            properties.is_deleted = AAZBoolType(
                serialized_name="isDeleted",
            )
            properties.items_search_key = AAZStrType(
                serialized_name="itemsSearchKey",
                flags={"required": True},
            )
            properties.labels = AAZListType()
            properties.number_of_lines_to_skip = AAZIntType(
                serialized_name="numberOfLinesToSkip",
            )
            properties.provider = AAZStrType(
                flags={"required": True},
            )
            properties.raw_content = AAZStrType(
                serialized_name="rawContent",
            )
            properties.source = AAZStrType()
            properties.source_type = AAZStrType(
                serialized_name="sourceType",
            )
            properties.tenant_id = AAZStrType(
                serialized_name="tenantId",
            )
            properties.updated = AAZStrType()
            properties.updated_by = AAZObjectType(
                serialized_name="updatedBy",
            )
            _build_schema_user_info_read(properties.updated_by)
            properties.upload_status = AAZStrType(
                serialized_name="uploadStatus",
            )
            properties.watchlist_alias = AAZStrType(
                serialized_name="watchlistAlias",
            )
            properties.watchlist_id = AAZStrType(
                serialized_name="watchlistId",
            )
            properties.watchlist_type = AAZStrType(
                serialized_name="watchlistType",
            )

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

            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},
            )

            return cls._schema_on_200_201


def _build_schema_user_info_create(_builder):
    if _builder is None:
        return
    _builder.set_prop("objectId", AAZStrType, ".object_id", typ_kwargs={"nullable": True})


_schema_user_info_read = None


def _build_schema_user_info_read(_schema):
    global _schema_user_info_read
    if _schema_user_info_read is not None:
        _schema.email = _schema_user_info_read.email
        _schema.name = _schema_user_info_read.name
        _schema.object_id = _schema_user_info_read.object_id
        return

    _schema_user_info_read = AAZObjectType()

    user_info_read = _schema_user_info_read
    user_info_read.email = AAZStrType(
        flags={"read_only": True},
    )
    user_info_read.name = AAZStrType(
        flags={"read_only": True},
    )
    user_info_read.object_id = AAZStrType(
        serialized_name="objectId",
        nullable=True,
    )

    _schema.email = _schema_user_info_read.email
    _schema.name = _schema_user_info_read.name
    _schema.object_id = _schema_user_info_read.object_id


__all__ = ["Create"]
