# --------------------------------------------------------------------------------------------
# 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 nsg rule update",
)
class Update(AAZCommand):
    """Update a network security group rule.

    :example: Update an NSG rule with a new wildcard destination address prefix.
        az network nsg rule update -g MyResourceGroup --nsg-name MyNsg -n MyNsgRule --destination-address-prefix '*'

    :example: Update a network security group rule. (autogenerated)
        az network nsg rule update --name MyNsgRule --nsg-name MyNsg --resource-group MyResourceGroup --source-address-prefixes 208.130.28/24
    """

    _aaz_info = {
        "version": "2022-01-01",
        "resources": [
            ["mgmt-plane", "/subscriptions/{}/resourcegroups/{}/providers/microsoft.network/networksecuritygroups/{}/securityrules/{}", "2022-01-01"],
        ]
    }

    AZ_SUPPORT_NO_WAIT = True

    AZ_SUPPORT_GENERIC_UPDATE = 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.nsg_name = AAZStrArg(
            options=["--nsg-name"],
            help="Name of the network security group.",
            required=True,
            id_part="name",
        )
        _args_schema.resource_group = AAZResourceGroupNameArg(
            required=True,
        )
        _args_schema.name = AAZStrArg(
            options=["-n", "--name"],
            help="Name of the network security group rule.",
            required=True,
            id_part="child_name_1",
        )
        _args_schema.access = AAZStrArg(
            options=["--access"],
            help="Allowed values: Allow, Deny.",
            enum={"Allow": "Allow", "Deny": "Deny"},
        )
        _args_schema.description = AAZStrArg(
            options=["--description"],
            help="Rule description.",
            nullable=True,
        )
        _args_schema.direction = AAZStrArg(
            options=["--direction"],
            help="Allowed values: Inbound, Outbound.",
            enum={"Inbound": "Inbound", "Outbound": "Outbound"},
        )
        _args_schema.priority = AAZIntArg(
            options=["--priority"],
            help="Rule priority, between 100 (highest priority) and 4096 (lowest priority). Must be unique for each rule in the collection.",
            nullable=True,
        )
        _args_schema.protocol = AAZStrArg(
            options=["--protocol"],
            help="etwork protocol this rule applies to.  Allowed values: *, Ah, Esp, Icmp, Tcp, Udp.",
            enum={"*": "*", "Ah": "Ah", "Esp": "Esp", "Icmp": "Icmp", "Tcp": "Tcp", "Udp": "Udp"},
        )

        # define Arg Group "Destination"

        _args_schema = cls._args_schema
        _args_schema.destination_address_prefixes = AAZListArg(
            options=["--destination-address-prefix", "--destination-address-prefixes"],
            arg_group="Destination",
            help="Space-separated list of CIDR prefixes or IP ranges. Alternatively, specify ONE of 'VirtualNetwork', 'AzureLoadBalancer', 'Internet' or '*' to match all IPs. Besides, it also supports all available Service Tags like 'ApiManagement', 'SqlManagement', 'AzureMonitor', etc. Default: *.",
            nullable=True,
        )
        _args_schema.destination_asgs_id = AAZListArg(
            options=["--destination-asgs-id"],
            arg_group="Destination",
            help="Space-separated list of application security group names or supports one application security group name or ID.",
            nullable=True,
        )
        _args_schema.destination_port_ranges = AAZListArg(
            options=["--destination-port-range", "--destination-port-ranges"],
            arg_group="Destination",
            help="Space-separated list of ports or port ranges between 0-65535. Use '*' to match all ports.  Default: 80.",
            nullable=True,
        )

        destination_address_prefixes = cls._args_schema.destination_address_prefixes
        destination_address_prefixes.Element = AAZStrArg(
            nullable=True,
        )

        destination_asgs_id = cls._args_schema.destination_asgs_id
        destination_asgs_id.Element = AAZObjectArg(
            nullable=True,
        )
        cls._build_args_application_security_group_update(destination_asgs_id.Element)

        destination_port_ranges = cls._args_schema.destination_port_ranges
        destination_port_ranges.Element = AAZStrArg(
            nullable=True,
        )

        # define Arg Group "SecurityRuleParameters"

        # define Arg Group "Source"

        _args_schema = cls._args_schema
        _args_schema.source_address_prefixes = AAZListArg(
            options=["--source-address-prefix", "--source-address-prefixes"],
            arg_group="Source",
            help="Space-separated list of CIDR prefixes or IP ranges. Alternatively, specify ONE of 'VirtualNetwork', 'AzureLoadBalancer', 'Internet' or '*' to match all IPs. Besides, it also supports all available Service Tags like 'ApiManagement', 'SqlManagement', 'AzureMonitor', etc. Default: *.",
            nullable=True,
        )
        _args_schema.source_asgs_id = AAZListArg(
            options=["--source-asgs-id"],
            arg_group="Source",
            help="Space-separated list of application security group names or IDs. Limited by backend server, temporarily this argument only supports one application security group name or ID.",
            nullable=True,
        )
        _args_schema.source_port_ranges = AAZListArg(
            options=["--source-port-range", "--source-port-ranges"],
            arg_group="Source",
            help="Space-separated list of ports or port ranges between 0-65535. Use '*' to match all ports.  Default: *.",
            nullable=True,
        )

        source_address_prefixes = cls._args_schema.source_address_prefixes
        source_address_prefixes.Element = AAZStrArg(
            nullable=True,
        )

        source_asgs_id = cls._args_schema.source_asgs_id
        source_asgs_id.Element = AAZObjectArg(
            nullable=True,
        )
        cls._build_args_application_security_group_update(source_asgs_id.Element)

        source_port_ranges = cls._args_schema.source_port_ranges
        source_port_ranges.Element = AAZStrArg(
            nullable=True,
        )
        return cls._args_schema

    _args_application_security_group_update = None

    @classmethod
    def _build_args_application_security_group_update(cls, _schema):
        if cls._args_application_security_group_update is not None:
            _schema.id = cls._args_application_security_group_update.id
            return

        cls._args_application_security_group_update = AAZObjectArg(
            nullable=True,
        )

        application_security_group_update = cls._args_application_security_group_update
        application_security_group_update.id = AAZResourceIdArg(
            options=["id"],
            help="Resource ID.",
            nullable=True,
            fmt=AAZResourceIdArgFormat(
                template="/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Network/applicationSecurityGroups/{}",
            ),
        )

        _schema.id = cls._args_application_security_group_update.id

    def _execute_operations(self):
        self.pre_operations()
        self.SecurityRulesGet(ctx=self.ctx)()
        self.pre_instance_update(self.ctx.vars.instance)
        self.InstanceUpdateByJson(ctx=self.ctx)()
        self.InstanceUpdateByGeneric(ctx=self.ctx)()
        self.post_instance_update(self.ctx.vars.instance)
        yield self.SecurityRulesCreateOrUpdate(ctx=self.ctx)()
        self.post_operations()

    @register_callback
    def pre_operations(self):
        pass

    @register_callback
    def post_operations(self):
        pass

    @register_callback
    def pre_instance_update(self, instance):
        pass

    @register_callback
    def post_instance_update(self, instance):
        pass

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

    class SecurityRulesGet(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]:
                return self.on_200(session)

            return self.on_error(session.http_response)

        @property
        def url(self):
            return self.client.format_url(
                "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}",
                **self.url_parameters
            )

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

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

        @property
        def url_parameters(self):
            parameters = {
                **self.serialize_url_param(
                    "networkSecurityGroupName", self.ctx.args.nsg_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "securityRuleName", self.ctx.args.name,
                    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(
                    "Accept", "application/json",
                ),
            }
            return parameters

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

            return cls._schema_on_200

    class SecurityRulesCreateOrUpdate(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_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 [200, 201]:
                return self.client.build_lro_polling(
                    self.ctx.args.no_wait,
                    session,
                    self.on_200_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/networkSecurityGroups/{networkSecurityGroupName}/securityRules/{securityRuleName}",
                **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(
                    "networkSecurityGroupName", self.ctx.args.nsg_name,
                    required=True,
                ),
                **self.serialize_url_param(
                    "resourceGroupName", self.ctx.args.resource_group,
                    required=True,
                ),
                **self.serialize_url_param(
                    "securityRuleName", self.ctx.args.name,
                    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,
                value=self.ctx.vars.instance,
            )

            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()
            _build_schema_security_rule_read(cls._schema_on_200_201)

            return cls._schema_on_200_201

    class InstanceUpdateByJson(AAZJsonInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance(self.ctx.vars.instance)

        def _update_instance(self, instance):
            _instance_value, _builder = self.new_content_builder(
                self.ctx.args,
                value=instance,
                typ=AAZObjectType
            )
            _builder.set_prop("name", AAZStrType, ".name")
            _builder.set_prop("properties", AAZObjectType, typ_kwargs={"flags": {"client_flatten": True}})

            properties = _builder.get(".properties")
            if properties is not None:
                properties.set_prop("access", AAZStrType, ".access", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("description", AAZStrType, ".description")
                properties.set_prop("destinationAddressPrefixes", AAZListType, ".destination_address_prefixes")
                properties.set_prop("destinationApplicationSecurityGroups", AAZListType, ".destination_asgs_id")
                properties.set_prop("destinationPortRanges", AAZListType, ".destination_port_ranges")
                properties.set_prop("direction", AAZStrType, ".direction", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("priority", AAZIntType, ".priority")
                properties.set_prop("protocol", AAZStrType, ".protocol", typ_kwargs={"flags": {"required": True}})
                properties.set_prop("sourceAddressPrefixes", AAZListType, ".source_address_prefixes")
                properties.set_prop("sourceApplicationSecurityGroups", AAZListType, ".source_asgs_id")
                properties.set_prop("sourcePortRanges", AAZListType, ".source_port_ranges")

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

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

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

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

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

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

            return _instance_value

    class InstanceUpdateByGeneric(AAZGenericInstanceUpdateOperation):

        def __call__(self, *args, **kwargs):
            self._update_instance_by_generic(
                self.ctx.vars.instance,
                self.ctx.generic_update_args
            )


def _build_schema_application_security_group_update(_builder):
    if _builder is None:
        return
    _builder.set_prop("id", AAZStrType, ".id")


_schema_application_security_group_read = None


def _build_schema_application_security_group_read(_schema):
    global _schema_application_security_group_read
    if _schema_application_security_group_read is not None:
        _schema.etag = _schema_application_security_group_read.etag
        _schema.id = _schema_application_security_group_read.id
        _schema.location = _schema_application_security_group_read.location
        _schema.name = _schema_application_security_group_read.name
        _schema.properties = _schema_application_security_group_read.properties
        _schema.tags = _schema_application_security_group_read.tags
        _schema.type = _schema_application_security_group_read.type
        return

    _schema_application_security_group_read = AAZObjectType()

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

    properties = _schema_application_security_group_read.properties
    properties.provisioning_state = AAZStrType(
        serialized_name="provisioningState",
        flags={"read_only": True},
    )
    properties.resource_guid = AAZStrType(
        serialized_name="resourceGuid",
        flags={"read_only": True},
    )

    tags = _schema_application_security_group_read.tags
    tags.Element = AAZStrType()

    _schema.etag = _schema_application_security_group_read.etag
    _schema.id = _schema_application_security_group_read.id
    _schema.location = _schema_application_security_group_read.location
    _schema.name = _schema_application_security_group_read.name
    _schema.properties = _schema_application_security_group_read.properties
    _schema.tags = _schema_application_security_group_read.tags
    _schema.type = _schema_application_security_group_read.type


_schema_security_rule_read = None


def _build_schema_security_rule_read(_schema):
    global _schema_security_rule_read
    if _schema_security_rule_read is not None:
        _schema.etag = _schema_security_rule_read.etag
        _schema.id = _schema_security_rule_read.id
        _schema.name = _schema_security_rule_read.name
        _schema.properties = _schema_security_rule_read.properties
        _schema.type = _schema_security_rule_read.type
        return

    _schema_security_rule_read = AAZObjectType()

    security_rule_read = _schema_security_rule_read
    security_rule_read.etag = AAZStrType(
        flags={"read_only": True},
    )
    security_rule_read.id = AAZStrType()
    security_rule_read.name = AAZStrType()
    security_rule_read.properties = AAZObjectType(
        flags={"client_flatten": True},
    )
    security_rule_read.type = AAZStrType()

    properties = _schema_security_rule_read.properties
    properties.access = AAZStrType(
        flags={"required": True},
    )
    properties.description = AAZStrType()
    properties.destination_address_prefix = AAZStrType(
        serialized_name="destinationAddressPrefix",
    )
    properties.destination_address_prefixes = AAZListType(
        serialized_name="destinationAddressPrefixes",
    )
    properties.destination_application_security_groups = AAZListType(
        serialized_name="destinationApplicationSecurityGroups",
    )
    properties.destination_port_range = AAZStrType(
        serialized_name="destinationPortRange",
    )
    properties.destination_port_ranges = AAZListType(
        serialized_name="destinationPortRanges",
    )
    properties.direction = AAZStrType(
        flags={"required": True},
    )
    properties.priority = AAZIntType()
    properties.protocol = AAZStrType(
        flags={"required": True},
    )
    properties.provisioning_state = AAZStrType(
        serialized_name="provisioningState",
        flags={"read_only": True},
    )
    properties.source_address_prefix = AAZStrType(
        serialized_name="sourceAddressPrefix",
    )
    properties.source_address_prefixes = AAZListType(
        serialized_name="sourceAddressPrefixes",
    )
    properties.source_application_security_groups = AAZListType(
        serialized_name="sourceApplicationSecurityGroups",
    )
    properties.source_port_range = AAZStrType(
        serialized_name="sourcePortRange",
    )
    properties.source_port_ranges = AAZListType(
        serialized_name="sourcePortRanges",
    )

    destination_address_prefixes = _schema_security_rule_read.properties.destination_address_prefixes
    destination_address_prefixes.Element = AAZStrType()

    destination_application_security_groups = _schema_security_rule_read.properties.destination_application_security_groups
    destination_application_security_groups.Element = AAZObjectType()
    _build_schema_application_security_group_read(destination_application_security_groups.Element)

    destination_port_ranges = _schema_security_rule_read.properties.destination_port_ranges
    destination_port_ranges.Element = AAZStrType()

    source_address_prefixes = _schema_security_rule_read.properties.source_address_prefixes
    source_address_prefixes.Element = AAZStrType()

    source_application_security_groups = _schema_security_rule_read.properties.source_application_security_groups
    source_application_security_groups.Element = AAZObjectType()
    _build_schema_application_security_group_read(source_application_security_groups.Element)

    source_port_ranges = _schema_security_rule_read.properties.source_port_ranges
    source_port_ranges.Element = AAZStrType()

    _schema.etag = _schema_security_rule_read.etag
    _schema.id = _schema_security_rule_read.id
    _schema.name = _schema_security_rule_read.name
    _schema.properties = _schema_security_rule_read.properties
    _schema.type = _schema_security_rule_read.type


__all__ = ["Update"]
