# --------------------------------------------------------------------------------------------
# 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(
    "network network-watcher packet-capture create",
)
class Create(AAZCommand):
    """Create and start a packet capture on the specified VM.

    :example: Create and start a packet capture 
        az network network-watcher packet-capture create --network-watcher-name "NetworkWatcher_eastus2euap" --packet-capture-name "clitestpcap" --resource-group "NetworkWatcherRG" --storage-location '{"storageId": "/subscriptions//resourceGroups//providers/Microsoft.Storage/storageAccounts/", "filePath": "C:\Captures\testByCli.cap"}' --target "/subscriptions/*****/resourceGroups//providers/Microsoft.Compute/virtualMachines/testVmName"
    """

    _aaz_info = {
        "version": "2024-05-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.network/networkwatchers/{}/packetcaptures/{}", "2024-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.network_watcher_name = AAZStrArg(
            options=["--network-watcher-name"],
            help="The name of the network watcher.",
            required=True,
        )
        _args_schema.packet_capture_name = AAZStrArg(
            options=["-n", "--name", "--packet-capture-name"],
            help="The name of the packet capture session.",
            required=True,
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )

        # define Arg Group "Properties"

        _args_schema = cls._args_schema
        _args_schema.bytes_to_capture_per_packet = AAZIntArg(
            options=["--bytes-to-capture", "--bytes-to-capture-per-packet"],
            arg_group="Properties",
            help="Number of bytes captured per packet, the remaining bytes are truncated.",
            default=0,
            fmt=AAZIntArgFormat(
                maximum=4294967295,
                minimum=0,
            ),
        )
        _args_schema.capture_settings = AAZObjectArg(
            options=["--capture-settings"],
            arg_group="Properties",
            help="The capture setting holds the 'FileCount', 'FileSizeInBytes', 'SessionTimeLimitInSeconds' values.",
        )
        _args_schema.continuous_capture = AAZBoolArg(
            options=["--continuous-capture"],
            arg_group="Properties",
            help="This continuous capture is a nullable boolean, which can hold 'null', 'true' or 'false' value. If we do not pass this parameter, it would be consider as 'null', default value is 'null'.",
        )
        _args_schema.filters = AAZListArg(
            options=["--filters"],
            arg_group="Properties",
            help="A list of packet capture filters.",
        )
        _args_schema.scope = AAZObjectArg(
            options=["--scope"],
            arg_group="Properties",
            help="A list of AzureVMSS instances which can be included or excluded to run packet capture. If both included and excluded are empty, then the packet capture will run on all instances of AzureVMSS.",
        )
        _args_schema.storage_location = AAZObjectArg(
            options=["--storage-location"],
            arg_group="Properties",
            help="The storage location for a packet capture session.",
            required=True,
        )
        _args_schema.target = AAZStrArg(
            options=["--target"],
            arg_group="Properties",
            help="The ID of the targeted resource, only AzureVM and AzureVMSS as target type are currently supported.",
            required=True,
        )
        _args_schema.target_type = AAZStrArg(
            options=["--target-type"],
            arg_group="Properties",
            help="Target type of the resource provided.",
            enum={"AzureVM": "AzureVM", "AzureVMSS": "AzureVMSS"},
        )
        _args_schema.time_limit_in_seconds = AAZIntArg(
            options=["--time-limit-in-seconds"],
            arg_group="Properties",
            help="Maximum duration of the capture session in seconds.",
            fmt=AAZIntArgFormat(
                maximum=18000,
                minimum=0,
            ),
        )
        _args_schema.total_bytes_per_session = AAZIntArg(
            options=["--total-bytes", "--total-bytes-per-session"],
            arg_group="Properties",
            help="Maximum size of the capture output.",
            fmt=AAZIntArgFormat(
                maximum=4294967295,
                minimum=0,
            ),
        )

        capture_settings = cls._args_schema.capture_settings
        capture_settings.file_count = AAZIntArg(
            options=["file-count"],
            help="Number of file count. Default value of count is 10 and maximum number is 10000.",
            default=10,
            fmt=AAZIntArgFormat(
                maximum=10000,
                minimum=0,
            ),
        )
        capture_settings.file_size_in_bytes = AAZIntArg(
            options=["file-size-in-bytes"],
            help="Number of bytes captured per packet. Default value in bytes 104857600 (100MB) and maximum in bytes 4294967295 (4GB).",
            default=104857600,
            fmt=AAZIntArgFormat(
                maximum=4294967295,
                minimum=0,
            ),
        )
        capture_settings.session_time_limit_in_seconds = AAZIntArg(
            options=["session-time-limit-in-seconds"],
            help="Maximum duration of the capture session in seconds is 604800s (7 days) for a file. Default value in second 86400s (1 day).",
            default=86400,
            fmt=AAZIntArgFormat(
                maximum=604800,
                minimum=0,
            ),
        )

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

        _element = cls._args_schema.filters.Element
        _element.local_ip_address = AAZStrArg(
            options=["local-ip-address"],
            help="Local IP Address to be filtered on. Notation: \"127.0.0.1\" for single address entry. \"127.0.0.1-127.0.0.255\" for range. \"127.0.0.1;127.0.0.5\"? for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.",
        )
        _element.local_port = AAZStrArg(
            options=["local-port"],
            help="Local port to be filtered on. Notation: \"80\" for single port entry.\"80-85\" for range. \"80;443;\" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.",
        )
        _element.protocol = AAZStrArg(
            options=["protocol"],
            help="Protocol to be filtered on.",
            default="Any",
            enum={"Any": "Any", "TCP": "TCP", "UDP": "UDP"},
        )
        _element.remote_ip_address = AAZStrArg(
            options=["remote-ip-address"],
            help="Local IP Address to be filtered on. Notation: \"127.0.0.1\" for single address entry. \"127.0.0.1-127.0.0.255\" for range. \"127.0.0.1;127.0.0.5;\" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.",
        )
        _element.remote_port = AAZStrArg(
            options=["remote-port"],
            help="Remote port to be filtered on. Notation: \"80\" for single port entry.\"80-85\" for range. \"80;443;\" for multiple entries. Multiple ranges not currently supported. Mixing ranges with multiple entries not currently supported. Default = null.",
        )

        scope = cls._args_schema.scope
        scope.exclude = AAZListArg(
            options=["exclude"],
            help="List of AzureVMSS instances which has to be excluded from the AzureVMSS from running packet capture.",
        )
        scope.include = AAZListArg(
            options=["include"],
            help="List of AzureVMSS instances to run packet capture on.",
        )

        exclude = cls._args_schema.scope.exclude
        exclude.Element = AAZStrArg()

        include = cls._args_schema.scope.include
        include.Element = AAZStrArg()

        storage_location = cls._args_schema.storage_location
        storage_location.file_path = AAZStrArg(
            options=["file-path"],
            help="This path is invalid if 'Continuous Capture' is provided with 'true' or 'false'. A valid local path on the targeting VM. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures. Required if no storage ID is provided, otherwise optional.",
        )
        storage_location.local_path = AAZStrArg(
            options=["local-path"],
            help="This path is valid if 'Continuous Capture' is provided with 'true' or 'false' and required if no storage ID is provided, otherwise optional. Must include the name of the capture file (*.cap). For linux virtual machine it must start with /var/captures.",
        )
        storage_location.storage_id = AAZStrArg(
            options=["storage-id"],
            help="The ID of the storage account to save the packet capture session. Required if no localPath or filePath is provided.",
        )
        storage_location.storage_path = AAZStrArg(
            options=["storage-path"],
            help="The URI of the storage path to save the packet capture. Must be a well-formed URI describing the location to save the packet capture.",
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.PacketCapturesCreate(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 PacketCapturesCreate(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_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 [201]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_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.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}",
                **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(
                    "networkWatcherName", self.ctx.args.network_watcher_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "packetCaptureName", self.ctx.args.packet_capture_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", "2024-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": {"required": True, "client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("bytesToCapturePerPacket", AAZIntType, ".bytes_to_capture_per_packet")
                properties.set_prop("captureSettings", AAZObjectType, ".capture_settings")
                properties.set_prop("continuousCapture", AAZBoolType, ".continuous_capture")
                properties.set_prop("filters", AAZListType, ".filters")
                properties.set_prop("scope", AAZObjectType, ".scope")
                properties.set_prop("storageLocation", AAZObjectType, ".storage_location", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("target", AAZStrType, ".target", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("targetType", AAZStrType, ".target_type")
                properties.set_prop("timeLimitInSeconds", AAZIntType, ".time_limit_in_seconds")
                properties.set_prop("totalBytesPerSession", AAZIntType, ".total_bytes_per_session")

            capture_settings = _builder.get(".properties.captureSettings")
            if capture_settings is not None:
                capture_settings.set_prop("fileCount", AAZIntType, ".file_count")
                capture_settings.set_prop("fileSizeInBytes", AAZIntType, ".file_size_in_bytes")
                capture_settings.set_prop("sessionTimeLimitInSeconds", AAZIntType, ".session_time_limit_in_seconds")

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

            _elements = _builder.get(".properties.filters[]")
            if _elements is not None:
                _elements.set_prop("localIPAddress", AAZStrType, ".local_ip_address")
                _elements.set_prop("localPort", AAZStrType, ".local_port")
                _elements.set_prop("protocol", AAZStrType, ".protocol")
                _elements.set_prop("remoteIPAddress", AAZStrType, ".remote_ip_address")
                _elements.set_prop("remotePort", AAZStrType, ".remote_port")

            scope = _builder.get(".properties.scope")
            if scope is not None:
                scope.set_prop("exclude", AAZListType, ".exclude")
                scope.set_prop("include", AAZListType, ".include")

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

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

            storage_location = _builder.get(".properties.storageLocation")
            if storage_location is not None:
                storage_location.set_prop("filePath", AAZStrType, ".file_path")
                storage_location.set_prop("localPath", AAZStrType, ".local_path")
                storage_location.set_prop("storageId", AAZStrType, ".storage_id")
                storage_location.set_prop("storagePath", AAZStrType, ".storage_path")

            return self.serialize_content(_content_value)

        def on_201(self, session):
            data = self.deserialize_http_content(session)
            self.ctx.set_var(
                "instance",
                data,
                schema_builder=self._build_schema_on_201
            )

        _schema_on_201 = None

        @classmethod
        def _build_schema_on_201(cls):
            if cls._schema_on_201 is not None:
                return cls._schema_on_201

            cls._schema_on_201 = AAZObjectType()

            _schema_on_201 = cls._schema_on_201
            _schema_on_201.etag = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_201.id = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_201.name = AAZStrType(
                flags={"read_only": True},
            )
            _schema_on_201.properties = AAZObjectType(
                flags={"client_flatten": True},
            )

            properties = cls._schema_on_201.properties
            properties.bytes_to_capture_per_packet = AAZIntType(
                serialized_name="bytesToCapturePerPacket",
            )
            properties.capture_settings = AAZObjectType(
                serialized_name="captureSettings",
            )
            properties.continuous_capture = AAZBoolType(
                serialized_name="continuousCapture",
            )
            properties.filters = AAZListType()
            properties.provisioning_state = AAZStrType(
                serialized_name="provisioningState",
                flags={"read_only": True},
            )
            properties.scope = AAZObjectType()
            properties.storage_location = AAZObjectType(
                serialized_name="storageLocation",
                flags={"required": True},
            )
            properties.target = AAZStrType(
                flags={"required": True},
            )
            properties.target_type = AAZStrType(
                serialized_name="targetType",
            )
            properties.time_limit_in_seconds = AAZIntType(
                serialized_name="timeLimitInSeconds",
            )
            properties.total_bytes_per_session = AAZIntType(
                serialized_name="totalBytesPerSession",
            )

            capture_settings = cls._schema_on_201.properties.capture_settings
            capture_settings.file_count = AAZIntType(
                serialized_name="fileCount",
            )
            capture_settings.file_size_in_bytes = AAZIntType(
                serialized_name="fileSizeInBytes",
            )
            capture_settings.session_time_limit_in_seconds = AAZIntType(
                serialized_name="sessionTimeLimitInSeconds",
            )

            filters = cls._schema_on_201.properties.filters
            filters.Element = AAZObjectType()

            _element = cls._schema_on_201.properties.filters.Element
            _element.local_ip_address = AAZStrType(
                serialized_name="localIPAddress",
            )
            _element.local_port = AAZStrType(
                serialized_name="localPort",
            )
            _element.protocol = AAZStrType()
            _element.remote_ip_address = AAZStrType(
                serialized_name="remoteIPAddress",
            )
            _element.remote_port = AAZStrType(
                serialized_name="remotePort",
            )

            scope = cls._schema_on_201.properties.scope
            scope.exclude = AAZListType()
            scope.include = AAZListType()

            exclude = cls._schema_on_201.properties.scope.exclude
            exclude.Element = AAZStrType()

            include = cls._schema_on_201.properties.scope.include
            include.Element = AAZStrType()

            storage_location = cls._schema_on_201.properties.storage_location
            storage_location.file_path = AAZStrType(
                serialized_name="filePath",
            )
            storage_location.local_path = AAZStrType(
                serialized_name="localPath",
            )
            storage_location.storage_id = AAZStrType(
                serialized_name="storageId",
            )
            storage_location.storage_path = AAZStrType(
                serialized_name="storagePath",
            )

            return cls._schema_on_201


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


__all__ = ["Create"]
