# --------------------------------------------------------------------------------------------
# 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 watcher run-configuration-diagnostic",
)
class RunConfigurationDiagnostic(AAZCommand):
    """Run a configuration diagnostic on a target resource.

    Requires that Network Watcher is enabled for the region in which the target is located.

    :example: Run configuration diagnostic on a VM with a single query.
        az network watcher run-configuration-diagnostic --resource {VM_ID} --direction Inbound --protocol TCP --source 12.11.12.14 --destination 10.1.1.4 --port 12100

    :example: Run configuration diagnostic on a VM with multiple queries.
        az network watcher run-configuration-diagnostic --resource {VM_ID} --queries '[{"direction": "Inbound", "protocol": "TCP", "source": "12.11.12.14", "destination": "10.1.1.4", "destinationPort": "12100"}, {"direction": "Inbound", "protocol": "TCP", "source": "12.11.12.0/32", "destination": "10.1.1.4", "destinationPort": "12100"}, {"direction": "Outbound", "protocol": "TCP", "source": "12.11.12.14", "destination": "10.1.1.4", "destinationPort": "12100"}]'
    """

    _aaz_info = {
        "version": "2022-01-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.network/networkwatchers/{}/networkconfigurationdiagnostic", "2022-01-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.watcher_name = AAZStrArg(
            options=["--watcher-name"],
            help="Name of the network watcher.",
            required=True,
            id_part="name",
        )
        _args_schema.watcher_rg = AAZResourceGroupNameArg(
            options=["--watcher-rg"],
            help="Name of the resource group the watcher is in.",
            required=True,
        )

        # define Arg Group "Parameters"

        # define Arg Group "Query"

        _args_schema = cls._args_schema
        _args_schema.queries = AAZListArg(
            options=["--queries"],
            arg_group="Query",
            help="JSON list of queries to use. Use `@{path}` to load from a file.",
            required=True,
        )

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

        _element = cls._args_schema.queries.Element
        _element.destination = AAZStrArg(
            options=["destination"],
            help="Traffic destination. Accepted values are: '*', IP Address/CIDR, Service Tag.",
            required=True,
        )
        _element.destination_port = AAZStrArg(
            options=["destination-port"],
            help="Traffic destination port. Accepted values are '*' and a single port in the range (0 - 65535).",
            required=True,
        )
        _element.direction = AAZStrArg(
            options=["direction"],
            help="The direction of the traffic.",
            required=True,
            enum={"Inbound": "Inbound", "Outbound": "Outbound"},
        )
        _element.protocol = AAZStrArg(
            options=["protocol"],
            help="Protocol to be verified on. Accepted values are '*', TCP, UDP.",
            required=True,
        )
        _element.source = AAZStrArg(
            options=["source"],
            help="Traffic source. Accepted values are '*', IP Address/CIDR, Service Tag.",
            required=True,
        )

        # define Arg Group "Target"

        _args_schema = cls._args_schema
        _args_schema.resource = AAZStrArg(
            options=["--resource"],
            arg_group="Target",
            help="Name or ID of the target resource to diagnose. If an ID is given, other resource arguments should not be given.",
            required=True,
        )
        return cls._args_schema

    def _execute_operations(self):
        self.pre_operations()
        yield self.NetworkWatchersGetNetworkConfigurationDiagnostic(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 NetworkWatchersGetNetworkConfigurationDiagnostic(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_200,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    path_format_arguments=self.url_parameters,
                )
            if session.http_response.status_code in [200]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200,
                    self.on_error,
                    lro_options={"final-state-via": "location"},
                    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}/networkConfigurationDiagnostic",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "networkWatcherName", self.ctx.args.watcher_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.watcher_rg,
                    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", "2022-01-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("profiles", AAZListType, ".queries", typ_kwargs={"flags": {"required": True}})
            _builder.set_prop("targetResourceId", AAZStrType, ".resource", typ_kwargs={"flags": {"required": True}})

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

            _elements = _builder.get(".profiles[]")
            if _elements is not None:
                _elements.set_prop("destination", AAZStrType, ".destination", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("destinationPort", AAZStrType, ".destination_port", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("direction", AAZStrType, ".direction", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("protocol", AAZStrType, ".protocol", typ_kwargs={"flags": {"required": True}})
                _elements.set_prop("source", AAZStrType, ".source", typ_kwargs={"flags": {"required": True}})

            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()
            _RunConfigurationDiagnosticHelper._build_schema_network_configuration_diagnostic_response_read(cls._schema_on_200)

            return cls._schema_on_200


class _RunConfigurationDiagnosticHelper:
    """Helper class for RunConfigurationDiagnostic"""

    _schema_network_configuration_diagnostic_response_read = None

    @classmethod
    def _build_schema_network_configuration_diagnostic_response_read(cls, _schema):
        if cls._schema_network_configuration_diagnostic_response_read is not None:
            _schema.results = cls._schema_network_configuration_diagnostic_response_read.results
            return

        cls._schema_network_configuration_diagnostic_response_read = _schema_network_configuration_diagnostic_response_read = AAZObjectType()

        network_configuration_diagnostic_response_read = _schema_network_configuration_diagnostic_response_read
        network_configuration_diagnostic_response_read.results = AAZListType(
            flags={"read_only": True},
        )

        results = _schema_network_configuration_diagnostic_response_read.results
        results.Element = AAZObjectType()

        _element = _schema_network_configuration_diagnostic_response_read.results.Element
        _element.network_security_group_result = AAZObjectType(
            serialized_name="networkSecurityGroupResult",
        )
        _element.profile = AAZObjectType()

        network_security_group_result = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result
        network_security_group_result.evaluated_network_security_groups = AAZListType(
            serialized_name="evaluatedNetworkSecurityGroups",
            flags={"read_only": True},
        )
        network_security_group_result.security_rule_access_result = AAZStrType(
            serialized_name="securityRuleAccessResult",
        )

        evaluated_network_security_groups = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result.evaluated_network_security_groups
        evaluated_network_security_groups.Element = AAZObjectType()

        _element = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result.evaluated_network_security_groups.Element
        _element.applied_to = AAZStrType(
            serialized_name="appliedTo",
        )
        _element.matched_rule = AAZObjectType(
            serialized_name="matchedRule",
        )
        _element.network_security_group_id = AAZStrType(
            serialized_name="networkSecurityGroupId",
        )
        _element.rules_evaluation_result = AAZListType(
            serialized_name="rulesEvaluationResult",
            flags={"read_only": True},
        )

        matched_rule = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result.evaluated_network_security_groups.Element.matched_rule
        matched_rule.action = AAZStrType()
        matched_rule.rule_name = AAZStrType(
            serialized_name="ruleName",
        )

        rules_evaluation_result = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result.evaluated_network_security_groups.Element.rules_evaluation_result
        rules_evaluation_result.Element = AAZObjectType()

        _element = _schema_network_configuration_diagnostic_response_read.results.Element.network_security_group_result.evaluated_network_security_groups.Element.rules_evaluation_result.Element
        _element.destination_matched = AAZBoolType(
            serialized_name="destinationMatched",
        )
        _element.destination_port_matched = AAZBoolType(
            serialized_name="destinationPortMatched",
        )
        _element.name = AAZStrType()
        _element.protocol_matched = AAZBoolType(
            serialized_name="protocolMatched",
        )
        _element.source_matched = AAZBoolType(
            serialized_name="sourceMatched",
        )
        _element.source_port_matched = AAZBoolType(
            serialized_name="sourcePortMatched",
        )

        profile = _schema_network_configuration_diagnostic_response_read.results.Element.profile
        profile.destination = AAZStrType(
            flags={"required": True},
        )
        profile.destination_port = AAZStrType(
            serialized_name="destinationPort",
            flags={"required": True},
        )
        profile.direction = AAZStrType(
            flags={"required": True},
        )
        profile.protocol = AAZStrType(
            flags={"required": True},
        )
        profile.source = AAZStrType(
            flags={"required": True},
        )

        _schema.results = cls._schema_network_configuration_diagnostic_response_read.results


__all__ = ["RunConfigurationDiagnostic"]
