"""
Autogenerated state module using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__

hub.exec.boto3.client.ec2.create_subnet
hub.exec.boto3.client.ec2.delete_subnet
hub.exec.boto3.client.ec2.describe_subnets
resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", name)
hub.tool.boto3.resource.exec(resource, create_instances, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, create_network_interface, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, create_tags, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, delete, *args, **kwargs)
"""
import copy
from typing import Any
from typing import Dict
from typing import List

import dict_tools.differ as differ

__contracts__ = ["resource"]

TREQ = {
    "absent": {
        "require": [
            "aws.ec2.vpc.absent",
        ],
    },
    "present": {
        "require": [
            "aws.ec2.vpc.present",
        ],
    },
}


async def present(
    hub,
    ctx,
    name: str,
    vpc: str,
    cidr_block: str,
    tag_specifications: List = None,
    availability_zone: str = None,
    availability_zone_id: str = None,
    ipv6_cidr_block: str = None,
    outpost_arn: str = None,
) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Creates a subnet in a specified VPC. You must specify an IPv4 CIDR block for the subnet. After you create a
    subnet, you can't change its CIDR block. The allowed block size is between a /16 netmask (65,536 IP addresses)
    and /28 netmask (16 IP addresses). The CIDR block must not overlap with the CIDR block of an existing subnet in
    the VPC. If you've associated an IPv6 CIDR block with your VPC, you can create a subnet with an IPv6 CIDR block
    that uses a /64 prefix length.   Amazon Web Services reserves both the first four and the last IPv4 address in
    each subnet's CIDR block. They're not available for use.  If you add more than one subnet to a VPC, they're set
    up in a star topology with a logical router in the middle. When you stop an instance in a subnet, it retains its
    private IPv4 address. It's therefore possible to have a subnet with no running instances (they're all stopped),
    but no remaining IP addresses available. For more information about subnets, see Your VPC and subnets in the
    Amazon Virtual Private Cloud User Guide.

    Args:
        name(Text): A name, ID, or JMES search path to identify the resource.
        tag_specifications(List, optional): The tags to assign to the subnet. Defaults to None.
        availability_zone(Text, optional): The Availability Zone or Local Zone for the subnet. Default: Amazon Web Services selects one for
            you. If you create more than one subnet in your VPC, we do not necessarily select a different
            zone for each subnet. To create a subnet in a Local Zone, set this value to the Local Zone ID,
            for example us-west-2-lax-1a. For information about the Regions that support Local Zones, see
            Available Regions in the Amazon Elastic Compute Cloud User Guide. To create a subnet in an
            Outpost, set this value to the Availability Zone for the Outpost and specify the Outpost ARN. Defaults to None.
        availability_zone_id(Text, optional): The AZ ID or the Local Zone ID of the subnet. Defaults to None.
        ipv6_cidr_block(Text, optional): The IPv6 network range for the subnet, in CIDR notation. The subnet size must use a /64 prefix
            length. Defaults to None.
        outpost_arn(Text, optional): The Amazon Resource Name (ARN) of the Outpost. If you specify an Outpost ARN, you must also
            specify the Availability Zone of the Outpost subnet. Defaults to None.
        vpc(Text): JMES search path or ID of the VPC.
        cidr_block(Text): The IPv4 network range for the subnet, in CIDR notation. For example, 10.0.0.0/24. We modify the
            specified CIDR block to its canonical form; for example, if you specify 100.68.0.18/18, we
            modify it to 100.68.0.0/18.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws_auto.ec2.subnet.present:
                - name: value
                - vpc: value
                - cidr_block: value
    """

    result = dict(comment="", changes=None, name=name, result=True)
    ret = await hub.exec.boto3.client.ec2.subnet.search(ctx, jmes_path=name)
    if ret["result"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]

    ret = await hub.exec.boto3.client.ec2.vpc.search(ctx, jmes_path=vpc)
    if ret["result"]:
        vpc = ret["ret"]

    resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", name)
    before = await hub.tool.boto3.resource.describe(resource)

    if before:
        result["comment"] = f"'{name}' already exists"
    else:
        try:
            ret = await hub.exec.boto3.client.ec2.create_subnet(
                ctx,
                DryRun=ctx.test,
                **{
                    "TagSpecifications": tag_specifications,
                    "AvailabilityZone": availability_zone,
                    "AvailabilityZoneId": availability_zone_id,
                    "Ipv6CidrBlock": ipv6_cidr_block,
                    "OutpostArn": outpost_arn,
                    "VpcId": vpc,
                    "CidrBlock": cidr_block,
                },
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            ret["comment"] = f"Created '{name}'"
            ret = await hub.exec.boto3.client.ec2.subnet.search(ctx, jmes_path=name)
            if ret["result"]:
                resource._id = ret["ret"]
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    # TODO perform other modifications as needed here
    ...

    try:
        after = await hub.tool.boto3.resource.describe(resource)
        result["changes"] = differ.deep_diff(before, after)
    except Exception as e:
        result["comment"] = str(e)
        result["result"] = False
    return result


async def absent(hub, ctx, name: str) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Deletes the specified subnet. You must terminate all running instances in the subnet before you can delete the
    subnet.

    Args:
        name(Text): The ID of the subnet or a name, ID, or JMES search path to identify the resource.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws_auto.ec2.subnet.absent:
                - name: value
                - subnet_id: value
    """

    result = dict(comment="", changes=None, name=name, result=True)
    ret = await hub.exec.boto3.client.ec2.subnet.search(ctx, jmes_path=name)
    if ret["result"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]

    resource = hub.tool.boto3.resource.create(ctx, "ec2", "Subnet", name)

    before = await hub.tool.boto3.resource.describe(resource)

    if not before:
        result["comment"] = f"'{name}' already absent"
    else:
        try:
            ret = await hub.exec.boto3.client.ec2.delete_subnet(
                ctx, DryRun=ctx.test, **{"SubnetId": name}
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            result["comment"] = f"Deleted '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    try:
        after = await hub.tool.boto3.resource.describe(resource)
        result["changes"] = differ.deep_diff(before, after)
    except Exception as e:
        result["comment"] = str(e)
        result["result"] = False
    return result


async def describe(hub, ctx) -> Dict[str, Dict[str, Any]]:
    result = {}
    ret = await hub.exec.boto3.client.ec2.describe_subnets(ctx)

    if not ret["result"]:
        hub.log.debug(f"Could not describe Subnets {ret['comment']}")
        return {}

    for subnet in ret["ret"]["Subnets"]:
        new_subnet = [
            {"vpc": subnet["VpcId"]},
            {"cidr_block": subnet["CidrBlock"]},
            {"tag_specifications": subnet.get("Tags", [])},
            {"availability_zone": subnet["AvailabilityZone"]},
            {"availability_zone_id": subnet["AvailabilityZoneId"]},
            {"outpost_arn": subnet.get("OutpostArn")},
        ]

        result[subnet["SubnetId"]] = {"aws.ec2.subnet.present": new_subnet}
        for i, data in enumerate(subnet["Ipv6CidrBlockAssociationSet"]):
            sub_subnet = copy.deepcopy(new_subnet)
            sub_subnet.append({"ipv6_cidrBlock": data["Ipv6CidrBlock"]})
            # The id needs to be in the name
            sub_subnet.append({"name": subnet["InstanceId"]})
            # Create a new state for this association set
            result[f"{subnet['SubnetId']}-{i}"] = {"aws.ec2.subnet.present": sub_subnet}
    return result
