"""
State module for managing EC2 VPc Endpoints.
"""
import copy
from dataclasses import field
from dataclasses import make_dataclass
from typing import Any
from typing import Dict
from typing import List

__contracts__ = ["resource"]


async def present(
    hub,
    ctx,
    name: str,
    vpc_id: str,
    service_name: str,
    resource_id: str = None,
    vpc_endpoint_type: str = None,
    policy_document: str = None,
    route_table_ids: List[str] = None,
    subnet_ids: List[str] = None,
    security_group_ids: List[str] = None,
    private_dns_enabled: bool = None,
    client_token: str = None,
    tags: Dict[str, Any]
    or List[
        make_dataclass("Tag", [("Key", str), ("Value", str, field(default=None))])
    ] = None,
    timeout: make_dataclass(
        "Timeout",
        [
            (
                "create",
                make_dataclass(
                    "CreateTimeout",
                    [
                        ("delay", int, field(default=None)),
                        ("max_attempts", int, field(default=None)),
                    ],
                ),
                field(default=None),
            ),
            (
                "update",
                make_dataclass(
                    "UpdateTimeout",
                    [
                        ("delay", int, field(default=None)),
                        ("max_attempts", int, field(default=None)),
                    ],
                ),
                field(default=None),
            ),
        ],
    ) = None,
) -> Dict[str, Any]:
    """Creates a VPC endpoint for a specified service.

    An endpoint enables you to create a private connection between your VPC and the service. The service may be provided
    by Amazon Web Services, an Amazon Web Services Marketplace Partner, or another Amazon Web Services account. For more
    information, see VPC Endpoints in the Amazon Virtual Private Cloud User Guide. A gateway endpoint serves as a target
    for a route in your route table for traffic destined for the Amazon Web Service. You can specify an endpoint policy
    to attach to the endpoint, which will control access to the service from your VPC. You can also specify the VPC route
    tables that use the endpoint. An interface endpoint is a network interface in your subnet that serves as an endpoint
    for communicating with the specified service. You can specify the subnets in which to create an endpoint, and the
    security groups to associate with the endpoint network interface. A GatewayLoadBalancer endpoint is a network
    interface in your subnet that serves an endpoint for communicating with a Gateway Load Balancer that you've configured
    as a VPC endpoint service. Use DescribeVpcEndpointServices to get a list of supported services.

    Args:
        name(str):
            An Idem name of the resource.

        vpc_id(str):
            AWS VPC ID.

        resource_id(str, Optional):
            AWS VPC Endpoint id.

        service_name(str): The service name.
            To get a list of available services, use the DescribeVpcEndpointServices request, or get the name from the
            service provider.

        vpc_endpoint_type(str, Optional):
            The type of endpoint. Default: Gateway. Defaults to Gateway.

        policy_document(str, Optional):
            (Interface and gateway endpoints) A policy to attach to the endpoint that controls access to the service.
            The policy must be in valid JSON format. If this parameter is not specified, we attach a default policy that
            allows full access to the service. Defaults to None.

        route_table_ids(list, Optional):
            (Gateway endpoint) One or more route table IDs. Defaults to None.

        subnet_ids(list, Optional):
            (Interface and Gateway Load Balancer endpoints) The ID of one or more subnets in which to create an endpoint
            network interface. For a Gateway Load Balancer endpoint, you can specify one subnet only. Defaults to None.

        security_group_ids(list, Optional):
            (Interface endpoint) The ID of one or more security groups to associate with the endpoint
            network interface. Defaults to None.

        private_dns_enabled(bool, Optional):
            (Interface endpoint) Indicates whether to associate a private hosted zone with the specified VPC. The private
            hosted zone contains a record set for the default public DNS name for the service for the Region (for example,
            kinesis.us-east-1.amazonaws.com), which resolves to the private IP addresses of the endpoint network
            interfaces in the VPC. This enables you to make requests to the default public DNS name for the service instead
            of the public DNS names that are automatically generated by the VPC endpoint service. To use a private hosted
            zone, you must set the following VPC attributes to true: enableDnsHostnames and enableDnsSupport. Use
            ModifyVpcAttribute to set the VPC attributes. Default: true. Defaults to None.

        client_token(str, Optional):
            Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Constraint: Maximum 64 ASCII characters. This field is autopopulated if not provided.

        tags(dict or list, Optional):
            Dict in the format of ``{tag-key: tag-value}`` or List of tags in the format of ``[{"Key": tag-key, "Value": tag-value}]``
            to associate with the VPC endpoint. Each tag consists of a key name and an associated value. Defaults to None.

            * Key (str, Optional):
                The key of the tag. Constraints: Tag keys are case-sensitive and accept a maximum of 127 Unicode characters.
                May not begin with aws:.

            * Value(str, Optional):
                The value of the tag. Constraints: Tag values are case-sensitive and accept a maximum of 256
                Unicode characters.

        timeout(dict, Optional):
            Timeout configuration for create/update of AWS VPC Endpoint.

            * create (dict):
                Timeout configuration for creating AWS VPC Endpoint

                * delay (int, Optional):
                    The amount of time in seconds to wait between attempts.
                * max_attempts (int, Optional):
                    Customized timeout configuration containing delay and max attempts.

            * update(dict, Optional):
                Timeout configuration for updating AWS VPC Endpoint

                * delay (int, Optional):
                    The amount of time in seconds to wait between attempts.

                * max_attempts (int, Optional):
                    Customized timeout configuration containing delay and max attempts.

    Request Syntax:
        .. code-block:: sls

            [vpc_endpoint-id]:
              aws.ec2.vpc_endpoint.present:
                - vpc_id: 'string'
                - service_name: 'string'
                - resource_id: 'string'
                - vpc_endpoint_type: 'string'
                - policy_document: 'string'
                - route_table_ids:
                  - 'string'
                - subnet_ids:
                  - 'string'
                - security_group_ids:
                  - 'string'
                - private_dns_enabled: 'Boolean'
                - client_token: 'string'
                - tag_specifications:
                - Key: 'string'
                  Value: 'string'

    Returns:
        Dict[str, Any]

    Examples:
        .. code-block:: sls

            vpce-1231231234:
              aws.ec2.vpc_endpoint.present:
                - vpc_id: vpc-123123123
                - service_name: com.amazonaws.us-west-2.s3
                - resource_id: vpce-1231231234
                - vpc_endpoint_type: Interface
                - private_dns_enabled: False
    """
    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    before = None

    if isinstance(tags, List):
        tags = hub.tool.aws.tag_utils.convert_tag_list_to_dict(tags)

    if resource_id:
        before = await hub.exec.aws.ec2.vpc_endpoint.get(
            ctx, resource_id=resource_id, name=name
        )
        if not before["result"] or not before["ret"]:
            result["result"] = False
            result["comment"] = before["comment"]
            return result
        result["old_state"] = copy.deepcopy(before["ret"])
        old_tags = result["old_state"].get("tags", None)
        plan_state = copy.deepcopy(result["old_state"])

        is_tag_update_required = tags is not None and tags != old_tags
        if is_tag_update_required:
            update_ret = await hub.tool.aws.ec2.tag.update_tags(
                ctx=ctx,
                resource_id=resource_id,
                old_tags=old_tags,
                new_tags=tags,
            )
            result["comment"] = result["comment"] + update_ret["comment"]
            if not update_ret["result"]:
                result["result"] = False
                return result
            if ctx.get("test", False) and update_ret["result"]:
                plan_state["tags"] = update_ret["ret"]

        hub.log.debug(f"Updating existing aws.ec2.vpc_endpoint '{name}'")
        ret = await hub.tool.aws.ec2.vpc_endpoint.update_vpc_endpoint(
            ctx,
            result["old_state"],
            resource_id=resource_id,
            policy_document=policy_document,
            route_table_ids=route_table_ids,
            subnet_ids=subnet_ids,
            security_group_ids=security_group_ids,
            private_dns_enabled=private_dns_enabled,
            timeout=timeout,
        )
        result["result"] = ret["result"]
        result["comment"] = ret["comment"]

        if not result["result"]:
            return result
        # if no update required then ret["result"] is True but ret["ret"] is None
        if not is_tag_update_required and not ret["ret"]:
            result["comment"] = hub.tool.aws.comment_utils.already_exists_comment(
                resource_type="aws.ec2.vpc_endpoint", name=name
            )
            result["new_state"] = copy.deepcopy(result["old_state"])
            return result
        if ctx.get("test", False):
            result["new_state"] = (
                ret["ret"] if ret["ret"] else copy.deepcopy(result["old_state"])
            )
            if plan_state.get("tags") is not None:
                result["new_state"]["tags"] = plan_state["tags"]
            return result
    else:
        if ctx.get("test", False):
            plan_state = {
                "name": name,
                "vpc_id": vpc_id,
                "service_name": service_name,
                "vpc_endpoint_type": vpc_endpoint_type,
                "policy_document": policy_document,
                "route_table_ids": route_table_ids,
                "subnet_ids": subnet_ids,
                "security_group_ids": security_group_ids,
                "private_dns_enabled": private_dns_enabled,
                "client_token": client_token,
                "tags": tags,
                "resource_id": "resource_id_known_after_present",
            }
            result["new_state"] = {k: v for k, v in plan_state.items() if v is not None}
            result["comment"] = (
                f"Would create aws.ec2.vpc_endpoint '{name}' and attach to vpc '{vpc_id}'",
            )
            return result

        hub.log.debug(f"Creating new aws.ec2.vpc_endpoint '{name}'")
        ret = await hub.exec.boto3.client.ec2.create_vpc_endpoint(
            ctx,
            ClientToken=client_token,
            VpcEndpointType=vpc_endpoint_type,
            VpcId=vpc_id,
            ServiceName=service_name,
            PolicyDocument=policy_document,
            RouteTableIds=route_table_ids,
            SubnetIds=subnet_ids,
            SecurityGroupIds=security_group_ids,
            PrivateDnsEnabled=private_dns_enabled,
            TagSpecifications=[
                {
                    "ResourceType": "vpc-endpoint",
                    "Tags": hub.tool.aws.tag_utils.convert_tag_dict_to_list(tags),
                }
            ]
            if tags
            else None,
        )
        result["result"] = ret["result"]
        if not result["result"]:
            result["comment"] = ret["comment"]
            return result
        resource_id = ret["ret"]["VpcEndpoint"]["VpcEndpointId"]
        hub.log.debug(
            f"Created new aws.ec2.vpc_endpoint '{name}' with resource_id: '{resource_id}'"
        )
        result["comment"] = (
            f"Created aws.ec2.vpc_endpoint: '{name}' attached to vpc: '{vpc_id}'",
        )
    try:
        after = await hub.exec.aws.ec2.vpc_endpoint.get(
            ctx, resource_id=resource_id, name=name
        )
        if not after["result"] or not after["ret"]:
            result["result"] = False
            result["comment"] = after["comment"]
            return result
        result["new_state"] = copy.deepcopy(after["ret"])
    except Exception as e:
        result["comment"] = result["comment"] + (str(e),)
        result["result"] = False
    return result


async def absent(
    hub, ctx, name: str, resource_id: str = None, timeout: Dict = None
) -> Dict[str, Any]:
    """
    Deletes the specified VPC endpoint.

    You can delete any of the following types of VPC endpoints. Gateway endpoint,   Gateway Load Balancer endpoint,
    Interface endpoint.

    The following rules apply when you delete a VPC endpoint:
        * When you delete a gateway endpoint, we delete the endpoint routes in the route tables that are associated with the endpoint.
        * When you delete a Gateway Load Balancer endpoint, we delete the endpoint network interfaces. You can only delete
          Gateway Load Balancer endpoints when the routes that are associated with the endpoint are deleted.
        * When you delete an interface endpoint, we delete the endpoint network interfaces.

    Args:
        name(str):
            An idem name of the resource

        resource_id(str, Optional):
            An AWS vpc_endpoint resource_id to identify the resource.

        timeout(dict, Optional):
            Timeout configuration for deleting the endpoint.

            * delete (dict):
                Timeout configuration for deleting the endpoint.

                * delay:
                    The amount of time in seconds to wait between attempts.

                * max_attempts:
                    Customized timeout configuration containing delay and max attempts.

    Request Syntax:
        .. code-block:: sls

            [vpc_endpoint-resource-id]:
              aws.ec2.vpc_endpoint.absent:
                - name: "string"
                - resource_id: "string"

    Returns:
        Dict[str, Any]

    Examples:
        .. code-block:: sls

            vpce-123123123:
              aws.ec2.vpc_endpoint.absent:
                - name: value
                - resource_id: vpce-123123123
    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    resource_already_absent_msg = hub.tool.aws.comment_utils.already_absent_comment(
        resource_type="aws.ec2.vpc_endpoint", name=name
    )
    if not resource_id:
        result["comment"] = resource_already_absent_msg
        return result
    before = await hub.exec.aws.ec2.vpc_endpoint.get(
        ctx, resource_id=resource_id, name=name
    )
    if not before["result"]:
        result["result"] = False
        result["comment"] = before["comment"]
        return result

    hub.log.debug(f"Attempting to delete aws.ec2.vpc_endpoint '{name}'")

    if not before["ret"]:
        result["comment"] = resource_already_absent_msg
        return result
    elif ctx.get("test", False):
        result["old_state"] = before["ret"]
        result["comment"] = (f"Would delete aws.ec2.vpc_endpoint '{name}'",)
        return result
    else:
        if before["ret"]["state"] == "deleted":
            result["comment"] = resource_already_absent_msg
            return result
        ret = await hub.exec.boto3.client.ec2.delete_vpc_endpoints(
            ctx, VpcEndpointIds=[resource_id]
        )
        result["result"] = ret["result"]
        if not result["result"]:
            result["comment"] = result["comment"] + (ret["comment"],)
            return result
        result["comment"] = result["comment"] + (f"Deleted '{name}'",)

        delete_waiter_acceptors = [
            {
                "matcher": "pathAll",
                "expected": "available",
                "state": "retry",
                "argument": "VpcEndpoints[].State",
            },
            {
                "matcher": "pathAll",
                "expected": "pending",
                "state": "retry",
                "argument": "VpcEndpoints[].State",
            },
            {
                "matcher": "pathAll",
                "expected": "deleted",
                "state": "success",
                "argument": "VpcEndpoints[].State",
            },
            {
                "matcher": "error",
                "expected": "InvalidVpcEndpointId.NotFound",
                "state": "success",
                "argument": "Error.Code",
            },
        ]
        waiter_config = hub.tool.aws.waiter_utils.create_waiter_config(
            default_delay=15,
            default_max_attempts=40,
            timeout_config=timeout.get("delete") if timeout else None,
        )
        endpoint_waiter = hub.tool.boto3.custom_waiter.waiter_wrapper(
            name="VpcEndpointDelete",
            operation="DescribeVpcEndpoints",
            argument=["Error.Code", "VpcEndpoints[].State"],
            acceptors=delete_waiter_acceptors,
            client=await hub.tool.boto3.client.get_client(ctx, "ec2"),
        )
        try:
            await hub.tool.boto3.client.wait(
                ctx,
                "ec2",
                "VpcEndpointDelete",
                endpoint_waiter,
                VpcEndpointIds=[resource_id],
                WaiterConfig=waiter_config,
            )
        except Exception as e:
            result["comment"] = result["comment"] + (str(e),)
            result["result"] = False
    result["old_state"] = before["ret"]
    return result


async def describe(hub, ctx) -> Dict[str, Dict[str, Any]]:
    """
    Describe the resource in a way that can be recreated/managed with the corresponding "present" function.

    Describes one or more of your VPC endpoints.

    Returns:
        Dict[str, Any]

    Examples:
        .. code-block:: bash

            $ idem describe aws.ec2.vpc_endpoint
    """

    result = {}
    ret = await hub.exec.aws.ec2.vpc_endpoint.list(
        ctx, name="aws.ec2.vpc_endpoint.describe"
    )
    if not ret["result"]:
        hub.log.debug(f"Could not describe aws.ec2.vpc_endpoint {ret['comment']}")
        return result

    for resource in ret["ret"]:
        result[resource.get("resource_id")] = {
            "aws.ec2.vpc_endpoint.present": [
                {parameter_key: parameter_value}
                for parameter_key, parameter_value in resource.items()
            ]
        }
    return result
