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

hub.exec.boto3.client.ec2.associate_route_table
hub.exec.boto3.client.ec2.create_route_table
hub.exec.boto3.client.ec2.delete_route_table
hub.exec.boto3.client.ec2.describe_route_tables
hub.exec.boto3.client.ec2.disassociate_route_table
resource = hub.tool.boto3.resource.create(ctx, "ec2", "RouteTable", name)
hub.tool.boto3.resource.exec(resource, associate_with_subnet, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, create_route, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, create_tags, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, delete, *args, **kwargs)
"""
from collections import OrderedDict
from typing import Any
from typing import Dict
from typing import List

__contracts__ = ["resource"]

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


async def present(
    hub,
    ctx,
    name: str,
    vpc_id: str,
    associations: List = None,
    routes: List = None,
    propagating_vgws: List = None,
    tags: List = None,
) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Creates a route table for the specified VPC. After you create a route table, you can add routes and associate
    the table with a subnet. For more information, see Route tables in the Amazon Virtual Private Cloud User Guide.

    Args:
        name(Text): A name, ID to identify the resource.
        vpc_id(Text): ID of the VPC.
        associations(list, optional): The associations between the route table and one or more subnets or a gateway.
            Defaults to None.
            * SubnetId (Text) -- The ID of the subnet. A subnet ID is not returned for an implicit association.
            * GatewayId (Text) -- The ID of the internet gateway or virtual private gateway.
        routes(list, optional): The routes in the route table.
            Defaults to None.
            DestinationCidrBlock (Text) -- The IPv4 CIDR block used for the destination match.
            DestinationIpv6CidrBlock (Text) -- The IPv6 CIDR block used for the destination match.
            DestinationPrefixListId (Text) -- The prefix of the Amazon Web Service.
            EgressOnlyInternetGatewayId (Text) -- The ID of the egress-only internet gateway.
            GatewayId (Text) -- The ID of a gateway attached to your VPC.
            InstanceId (Text) -- The ID of a NAT instance in your VPC.
            InstanceOwnerId (Text) -- The ID of Amazon Web Services account that owns the instance.
            NatGatewayId (Text) -- The ID of a NAT gateway.
            TransitGatewayId (Text) -- The ID of a transit gateway.
            LocalGatewayId (Text) -- The ID of the local gateway.
            CarrierGatewayId (Text) -- The ID of the carrier gateway.
            NetworkInterfaceId (Text) -- The ID of the network interface.
            VpcPeeringConnectionId (Text) -- The ID of a VPC peering connection.
            CoreNetworkArn (Text) -- The Amazon Resource Name (ARN) of the core network.
        propagating_vgws(list, optional): Any virtual private gateway (VGW) propagating routes.
            GatewayId (Text) -- The ID of the virtual private gateway.
        tags(List, optional): The tags to assign to the route_table. Defaults to None.
            * Key (string) -- The key of the tag. Tag keys are case-sensitive and accept a maximum of 127 Unicode characters. May not begin with aws: .
            * Value (string) -- The value of the tag. Tag values are case-sensitive and accept a maximum of 255 Unicode characters.

    Request Syntax:
        [route_table-resource-id]:
          aws.ec2.route_table.present:
          - vpc_id: 'string'
          - associations:
            - GatewayId: 'string'
            - SubnetId: 'string'
          - routes:
            - DestinationCidrBlock: 'string'
              GatewayId: 'string'
          - propagating_vgws:
             - 'string'
          - tags:
            - Key: 'string'
              Value: 'string'

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            rtb-0944888360196462c:
              aws.ec2.route_table.present:
              - vpc_id: vpc-02850adfa9f6fc916
              - associations:
                - GatewayId: vgw-0334141b528f99316
                - SubnetId: subnet-0610f7c1a12a1af6a
              - routes:
                - DestinationCidrBlock: 198.31.0.0/16
                  GatewayId: local
              - propagating_vgws:
                 - vgw-0334141b528f99316
              - tags:
                - Key: Name
                  Value: route-table-association-test
    """

    result = dict(comment="", old_state=None, new_state=None, name=name, result=True)
    created_route_table_id = name
    update_tags = False
    before = await hub.exec.boto3.client.ec2.describe_route_tables(
        ctx, DryRun=False, RouteTableIds=[name]
    )

    if before and before["result"] and before["ret"].get("RouteTables"):
        route_table_resource = before["ret"].get("RouteTables")[0]
        update_ret = await hub.exec.aws.ec2.route_table.update_associations_routes(
            ctx=ctx,
            route_table_id=route_table_resource.get("RouteTableId"),
            old_routes=route_table_resource.get("Routes"),
            new_routes=routes,
            old_associations=route_table_resource.get("Associations"),
            new_associations=associations,
            old_propagating_vgws=route_table_resource.get("PropagatingVgws"),
            new_propagating_vgws=propagating_vgws,
        )
        update_comment = update_ret["comment"]
        if not update_ret["result"]:
            result["result"] = False
        update_tags_comment = ""
        if result["result"] and tags is not None:
            # Update tags
            update_ret = await hub.exec.aws.ec2.tag.update_tags(
                ctx=ctx,
                resource_id=route_table_resource.get("RouteTableId"),
                old_tags=route_table_resource.get("Tags"),
                new_tags=tags,
            )
            update_tags = True
            update_tags_comment = update_ret["comment"]
            if not update_ret["result"]:
                result["result"] = False
        result[
            "comment"
        ] = f"{name} is already present. {update_comment}. {update_tags_comment}"
    else:
        try:
            ret = await hub.exec.boto3.client.ec2.create_route_table(
                ctx,
                DryRun=False,
                TagSpecifications=[{"ResourceType": "route-table", "Tags": tags}]
                if tags
                else None,
                VpcId=vpc_id,
            )
            result["result"] = ret["ret"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            created_route_table_id = ret["ret"]["RouteTable"]["RouteTableId"]
            ret["comment"] = f"Created '{created_route_table_id}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"
            result["result"] = False

    after = None
    if update_tags or created_route_table_id is not None:
        after = await hub.exec.boto3.client.ec2.describe_route_tables(
            ctx, DryRun=False, RouteTableIds=[created_route_table_id]
        )
    if before["result"] and before["ret"].get("RouteTables"):
        result["old_state"] = before["ret"]["RouteTables"][0]
    if after and after["result"] and after["ret"].get("RouteTables"):
        result["new_state"] = after["ret"]["RouteTables"][0]
    return result


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

    Deletes the specified route table. You must disassociate the route table from any subnets before you can delete
    it. You can't delete the main route table.

    Args:
        name(Text): A name or ID to identify the resource.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws.ec2.route_table.absent:
                - name: value
    """

    result = dict(comment="", old_state=None, new_state=None, name=name, result=True)
    route_table_id_list = [name]
    before = await hub.exec.boto3.client.ec2.describe_route_tables(
        ctx, DryRun=False, RouteTableIds=route_table_id_list
    )
    if before and not before["result"]:
        result["comment"] = before["comment"]
        result["result"] = False
        return result

    if before["result"] and before["ret"].get("RouteTables"):
        result["old_state"] = before["ret"]["RouteTables"][0]

    if not before:
        result["comment"] = f"'{name}' already absent"
    elif ctx.get("test", False):
        result["comment"] = f"Would delete aws.ec2.route_table {name}"
        return result
    else:
        try:
            # we have to disassociate all subnets and gateways before we can delete route table
            if before["ret"] and before["ret"]["RouteTables"]:
                old_route_table = before["ret"]["RouteTables"][0]
                if old_route_table.get("Associations"):
                    for association in old_route_table.get("Associations"):
                        if association.get("Main") is not True:
                            ret = await hub.exec.boto3.client.ec2.disassociate_route_table(
                                ctx,
                                AssociationId=association.get(
                                    "RouteTableAssociationId"
                                ),
                            )
                            if not ret.get("result"):
                                result["comment"] = ret["comment"]
                                result["result"] = False
                                return result
            ret = await hub.exec.boto3.client.ec2.delete_route_table(
                ctx, RouteTableId=name
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                result["result"] = False
                return result
            result["comment"] = f"Deleted '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"
    return result


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

    Describe the resource in a way that can be recreated/managed with the corresponding "present" function


    Describes one or more of your route tables. Each subnet in your VPC must be associated with a route table. If a
    subnet is not explicitly associated with any route table, it is implicitly associated with the main route table.
    This command does not return the subnet ID for implicit associations. For more information, see Route tables in
    the Amazon Virtual Private Cloud User Guide.


    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.ec2.route_table
    """

    result = {}

    ret = await hub.exec.boto3.client.ec2.describe_route_tables(ctx)
    if not ret["result"]:
        hub.log.debug(f"Could not describe route_table {ret['comment']}")
        return result
    describe_parameters = OrderedDict(
        {
            "VpcId": "vpc_id",
            "PropagatingVgws": "propagating_vgws",
            "Tags": "tags",
        }
    )
    for route_table in ret["ret"]["RouteTables"]:
        route_table_id = route_table.get("RouteTableId")

        new_route_table = []
        for parameter_old_key, parameter_new_key in describe_parameters.items():
            if route_table.get(parameter_old_key) is not None:
                new_route_table.append(
                    {parameter_new_key: route_table.get(parameter_old_key)}
                )
        # Add only required parameters in Describe
        if route_table.get("Routes"):
            routes_to_add = []
            for route_to_add in route_table.get("Routes"):
                new_route = route_to_add
                if route_to_add.get("State") == "active":
                    del new_route["State"]
                    del new_route["Origin"]
                    routes_to_add.append(new_route)
            new_route_table.append({"routes": routes_to_add})

        if route_table.get("Associations"):
            associations_to_add = []
            for association_to_add in route_table.get("Associations"):
                new_association = association_to_add
                if (
                    association_to_add.get("AssociationState").get("State")
                    == "associated"
                    and not new_association["Main"]
                ):
                    del new_association["AssociationState"]
                    del new_association["Main"]
                    associations_to_add.append(new_association)
            new_route_table.append({"associations": associations_to_add})
        result[route_table_id] = {"aws.ec2.route_table.present": new_route_table}
    return result
