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

hub.exec.boto3.client.ec2.create_vpc_endpoint
hub.exec.boto3.client.ec2.delete_vpc_endpoints
hub.exec.boto3.client.ec2.describe_vpc_endpoints
hub.exec.boto3.client.ec2.modify_vpc_endpoint
"""
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: List[Dict[str, Any]] or Dict[str, Any] = None,
    timeout: make_dataclass(
        "Timeout",
        [
            (
                "create",
                make_dataclass(
                    "CreateTimeout",
                    [
                        ("delay", int, field(default=0)),
                        ("max_attempts", int, field(default=0)),
                    ],
                ),
                field(default=None),
            ),
            (
                "update",
                make_dataclass(
                    "UpdateTimeout",
                    [
                        ("delay", int, field(default=0)),
                        ("max_attempts", int, field(default=0)),
                    ],
                ),
                field(default=None),
            ),
        ],
    ) = None,
) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    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(Text): An Idem name of the resource.
        vpc_id(Text): AWS VPC ID.
        resource_id(Text, optional): AWS VPC Endpoint id.
        service_name(Text): 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(Text, optional): The type of endpoint. Default: Gateway. Defaults to Gateway.
        policy_document(Text, 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(Text, 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, 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, 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/deletion of AWS IAM Policy.
            * create (Dict): Timeout configuration for creating AWS IAM Policy
                * 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 IAM Policy
                * 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:
        [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 resource_id:
        before = await hub.exec.boto3.client.ec2.describe_vpc_endpoints(
            ctx, VpcEndpointIds=[resource_id]
        )
        if not before["result"]:
            result["result"] = False
            result["comment"] = result["comment"] + before["comment"]
            return result

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

    if before and before["ret"].get("VpcEndpoints"):
        result[
            "old_state"
        ] = hub.tool.aws.ec2.conversion_utils.convert_raw_vpc_endpoint_to_present(
            raw_resource=before["ret"]["VpcEndpoints"][0], idem_resource_name=name
        )
        old_tags = result["old_state"].get("tags", None)
        plan_state = copy.deepcopy(result["old_state"])
        if tags is not None and tags != old_tags:
            update_ret = await hub.exec.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.exec.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 ctx.get("test", False):
            result["new_state"] = ret["ret"]
            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,
            }
            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.boto3.client.ec2.describe_vpc_endpoints(
            ctx, VpcEndpointIds=[resource_id]
        )
        result[
            "new_state"
        ] = hub.tool.aws.ec2.conversion_utils.convert_raw_vpc_endpoint_to_present(
            raw_resource=after["ret"]["VpcEndpoints"][0], idem_resource_name=name
        )
    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]:
    r"""
    **Autogenerated function**

    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(Text): An idem name of the resource
        resource_id(Text, 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.

    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.boto3.client.ec2.describe_vpc_endpoints(
        ctx, VpcEndpointIds=[resource_id]
    )
    hub.log.debug(f"Attempting to delete aws.ec2.vpc_endpoint '{name}'")

    if not (before["ret"] and before["result"]):
        result["comment"] = resource_already_absent_msg
        return result
    elif ctx.get("test", False):
        result[
            "old_state"
        ] = hub.tool.aws.ec2.conversion_utils.convert_raw_vpc_endpoint_to_present(
            raw_resource=before["ret"]["VpcEndpoints"][0], idem_resource_name=name
        )
        result["comment"] = (f"Would delete aws.ec2.vpc_endpoint '{name}'",)
        return result
    else:
        if before["ret"]["VpcEndpoints"][0]["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=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
    if before["result"] and before["ret"].get("VpcEndpoints"):
        result[
            "old_state"
        ] = hub.tool.aws.ec2.conversion_utils.convert_raw_vpc_endpoint_to_present(
            raw_resource=before["ret"]["VpcEndpoints"][0], idem_resource_name=name
        )
    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 VPC endpoints.


    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.ec2.vpc_endpoint
    """

    result = {}
    ret = await hub.exec.boto3.client.ec2.describe_vpc_endpoints(ctx)

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

    for vpc_endpoint in ret["ret"]["VpcEndpoints"]:
        resource_id = vpc_endpoint.get("VpcEndpointId")
        resource_translated = (
            hub.tool.aws.ec2.conversion_utils.convert_raw_vpc_endpoint_to_present(
                vpc_endpoint, idem_resource_name=resource_id
            )
        )
        result[resource_id] = {
            "aws.ec2.vpc_endpoint.present": [
                {parameter_key: parameter_value}
                for parameter_key, parameter_value in resource_translated.items()
            ]
        }

    return result
