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

hub.exec.boto3.client.eks.create_cluster
hub.exec.boto3.client.eks.delete_cluster
hub.exec.boto3.client.eks.deregister_cluster
hub.exec.boto3.client.eks.describe_cluster
hub.exec.boto3.client.eks.list_clusters
hub.exec.boto3.client.eks.register_cluster
"""
import copy
from typing import Any
from typing import Dict

__contracts__ = ["resource"]

TREQ = {
    "absent": {
        "require": [
            "aws.eks.nodegroup.absent",
            "aws.eks.addon.absent",
            "aws.eks.fargate_profile.absent",
        ],
    },
    "present": {
        "require": [
            "aws.ec2.subnet.present",
            "aws.iam.role.present",
        ],
    },
}

create_attempts = 60
update_attempts = 120


async def present(
    hub,
    ctx,
    name: str,
    role_arn: str,
    resources_vpc_config: Dict,
    resource_id: str = None,
    version: str = None,
    kubernetes_network_config: Dict = None,
    logging: Dict = None,
    encryption_config: Dict = None,
    tags: Dict[str, str] = None,
    timeout: Dict = None,
) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Creates an Amazon EKS control plane.  The Amazon EKS control plane consists of control plane instances that run
    the Kubernetes software, such as etcd and the API server. The control plane runs in an account managed by Amazon
    Web Services, and the Kubernetes API is exposed by the Amazon EKS API server endpoint. Each Amazon EKS cluster
    control plane is single tenant and unique. It runs on its own set of Amazon EC2 instances. The cluster control
    plane is provisioned across multiple Availability Zones and fronted by an Elastic Load Balancing Network Load
    Balancer. Amazon EKS also provisions elastic network interfaces in your VPC subnets to provide connectivity from
    the control plane instances to the nodes (for example, to support kubectl exec, logs, and proxy data flows).
    Amazon EKS nodes run in your Amazon Web Services account and connect to your cluster's control plane over the
    Kubernetes API server endpoint and a certificate file that is created for your cluster. In most cases, it takes
    several minutes to create a cluster. After you create an Amazon EKS cluster, you must configure your Kubernetes
    tooling to communicate with the API server and launch nodes into your cluster. For more information, see
    Managing Cluster Authentication and Launching Amazon EKS nodes in the Amazon EKS User Guide.

    Args:
        name(Text): An Idem name of the EKS cluster resource.
        version(Text): The desired Kubernetes version for your cluster
        role_arn(Text): The Amazon Resource Name (ARN) of the IAM role that provides permissions for the Kubernetes
            control plane to make calls to Amazon Web Services API operations on your behalf. For more information,
            see Amazon EKS Service IAM Role in the * Amazon EKS User Guide *
        resources_vpc_config(Dict): The VPC configuration that's used by the cluster control plane. Amazon
            EKS VPC resources have specific requirements to work properly with Kubernetes. For more information,
            see Cluster VPC Considerations and Cluster Security Group Considerations in the Amazon EKS User Guide . You
            must specify at least two subnets. You can specify up to five security groups. However, we recommend that you
            use a dedicated security group for your cluster control plane.
        resource_id(Text, optional): AWS EKS cluster name to identify the resource
        kubernetes_network_config(Dict, optional): The Kubernetes network configuration for the cluster.
        logging(Dict, optional): Enable or disable exporting the Kubernetes control plane logs for your cluster to
            CloudWatch Logs. By default, cluster control plane logs aren't exported to CloudWatch Logs. For more
            information, see Amazon EKS Cluster control plane logs in the * Amazon EKS User Guide *
        encryption_config(Dict, optional): The encryption configuration for the cluster.
        tags(Dict, optional): The metadata to apply to the cluster to assist with categorization and organization.
        timeout(Dict, optional): Timeout configuration for creating or updating cluster.
            * create (Dict) -- Timeout configuration for creating cluster
                * delay(int, default=60) -- The amount of time in seconds to wait between attempts.
                * max_attempts(int, default=40) -- Customized timeout configuration containing delay and max attempts.
            * update (string) -- Timeout configuration for updating cluster
                * delay(int, default=60) -- The amount of time in seconds to wait between attempts.
                * max_attempts(int, default=40) -- Customized timeout configuration containing delay and max attempts.

    Request Syntax:
        [eks-cluster-resource-name]:
            aws.eks.cluster.present:
              - role_arn: 'string'
              - version: 'string'
              - resource_id: 'string'
              - resources_vpc_config:
                  endpointPrivateAccess: boolean
                  endpointPublicAccess: boolean
                  publicAccessCidrs: list
                  securityGroupIds:
                  - 'string'
                  subnetIds:
                  - 'string'
                  - 'string'
              - kubernetes_network_config:
                  ipFamily: 'string'
                  serviceIpv4Cidr: 'string'
              - logging:
                  clusterLogging:
                  - enabled: boolean
                    types:
                    - 'string'
                    - 'string'
                  - enabled: boolean
                    types:
                    - 'string'
                    - 'string'
                    - 'string'
              - tags:
                 'string': 'string'
              - timeout:
                   create:
                      delay: 'integer'
                      max_attempts: 'integer'
                   update:
                      delay: 'integer'
                      max_attempts: 'integer

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            my_cluster:
              aws.eks.cluster.present:
              - role_arn: arn:aws:iam::202236654445:role/ek1
              - version: '1.21'
              - resource_id: eks-e45k5n423
              - resources_vpc_config:
                  endpointPrivateAccess: true
                  endpointPublicAccess: false
                  publicAccessCidrs: []
                  securityGroupIds:
                  - sg-000b8c21b6b480577
                  subnetIds:
                  - subnet-07bc4715744fb7b39
                  - subnet-0aa66edffb00d8881
              - kubernetes_network_config:
                  ipFamily: ipv4
                  serviceIpv4Cidr: 172.20.0.0/16
              - logging:
                  clusterLogging:
                  - enabled: true
                    types:
                    - api
                    - audit
                  - enabled: false
                    types:
                    - authenticator
                    - controllerManager
                    - scheduler
              - tags:
                  Name: eks-cluster-name

    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    before = None
    resource_updated = False
    if resource_id:
        before = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=resource_id)
        if not before["result"]:
            if not ("ResourceNotFoundException" in before["comment"][0]):
                result["result"] = False
                result["comment"] = before["comment"]
                return result
    try:
        if before and before["ret"]:
            result[
                "old_state"
            ] = hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
                raw_resource=before["ret"]["cluster"], idem_resource_name=name
            )
            client_request_token = result["old_state"].get("client_request_token", None)
            plan_state = copy.deepcopy(result["old_state"])

            # update cluster
            update_ret = await hub.exec.aws.eks.cluster.update_cluster(
                ctx=ctx,
                name=name,
                before=result["old_state"],
                version=version,
                encryption_config=encryption_config,
                resources_vpc_config=resources_vpc_config,
                logging=logging,
                client_request_token=client_request_token,
                timeout=timeout,
            )
            result["comment"] = update_ret["comment"]
            result["result"] = update_ret["result"]
            resource_updated = bool(update_ret["ret"])
            if update_ret["ret"] and ctx.get("test", False):
                result["comment"] = result["comment"] + (
                    f"Would update aws.eks.cluster '{name}'",
                )
                for cluster_param in update_ret["ret"]:
                    plan_state[cluster_param] = update_ret["ret"][cluster_param]
            # update tags
            if tags is not None:
                update_tags_ret = await hub.exec.aws.eks.tag.update_eks_tags(
                    ctx=ctx,
                    resource_arn=result["old_state"].get("arn"),
                    old_tags=result["old_state"].get("tags"),
                    new_tags=tags,
                )
                result["comment"] = result["comment"] + update_tags_ret["comment"]
                result["result"] = result["result"] and update_tags_ret["result"]
                resource_updated = resource_updated or bool(update_tags_ret["ret"])

                if ctx.get("test", False) and update_tags_ret["ret"]:
                    plan_state["tags"] = update_tags_ret["ret"].get("tags")
        else:
            if ctx.get("test", False):
                result["new_state"] = hub.tool.aws.test_state_utils.generate_test_state(
                    enforced_state={},
                    desired_state={
                        "name": name,
                        "version": version,
                        "role_arn": role_arn,
                        "resources_vpc_config": resources_vpc_config,
                        "kubernetes_network_config": kubernetes_network_config,
                        "logging": logging,
                        "encryption_config": encryption_config,
                        "tags": tags,
                    },
                )
                result["comment"] = hub.tool.aws.comment_utils.would_create_comment(
                    resource_type="aws.eks.cluster", name=name
                )
                return result

            try:
                ret = await hub.exec.boto3.client.eks.create_cluster(
                    ctx,
                    name=name,
                    version=version,
                    roleArn=role_arn,
                    resourcesVpcConfig=resources_vpc_config,
                    kubernetesNetworkConfig=kubernetes_network_config,
                    logging=logging,
                    encryptionConfig=encryption_config,
                    tags=tags,
                )
                result["result"] = ret["result"]
                if not result["result"]:
                    result["comment"] = ret["comment"]
                    return result

                resource_id = ret["ret"]["cluster"]["name"]
                waiter_ret = await hub.exec.aws.eks.cluster.cluster_waiter(
                    ctx, name, resource_id, timeout, "create"
                )
                if not waiter_ret["result"]:
                    result["result"] = False
                    result["comment"] = result["comment"] + waiter_ret["comment"]
                result["comment"] = hub.tool.aws.comment_utils.create_comment(
                    resource_type="aws.eks.cluster", name=name
                )
            except hub.tool.boto3.exception.ClientError as e:
                result["comment"] = result["comment"] + (
                    f"{e.__class__.__name__}: {e}",
                )
                result["result"] = False
    except Exception as e1:
        result["comment"] = result["comment"] + (f"{e1.__class__.__name__}: {e1}",)
        result["result"] = False
        return result

    try:
        if ctx.get("test", False):
            result["new_state"] = plan_state
        elif (not before) or resource_updated:
            after = await hub.exec.boto3.client.eks.describe_cluster(
                ctx, name=resource_id
            )
            result[
                "new_state"
            ] = hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
                raw_resource=after["ret"]["cluster"], idem_resource_name=name
            )
        else:
            result["new_state"] = copy.deepcopy(result["old_state"])
    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 Amazon EKS cluster control plane. If you have active services in your cluster that are associated
    with a load balancer, you must delete those services before deleting the cluster so that the load balancers are
    deleted properly. Otherwise, you can have orphaned resources in your VPC that prevent you from being able to
    delete the VPC. For more information, see Deleting a Cluster in the Amazon EKS User Guide. If you have managed
    node groups or Fargate profiles attached to the cluster, you must delete them first. For more information, see
    DeleteNodegroup and DeleteFargateProfile.

    Args:
        name(Text): An Idem name of the EKS cluster resource.
        resource_id(Text, optional): AWS EKS cluster name. Idem automatically considers this resource being absent
         if this field is not specified.
        timeout(Dict, optional): Timeout configuration for deleting cluster.
            * delete (Dict) -- Timeout configuration for deleting cluster
                * delay(int, default=60) -- The amount of time in seconds to wait between attempts.
                * max_attempts(int, default=40) -- Customized timeout configuration containing delay and max attempts.


    Request syntax:
        [eks_cluster_name]:
          aws.eks.cluster.absent:
            - name: 'string'
            - resource_id: 'string'

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            eks_cluster_prod:
              aws.eks.cluster.absent:
                - name: eks_cluster_prod
                - resource_id: eks_cluster_prod
    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    if not resource_id:
        result["comment"] = hub.tool.aws.comment_utils.already_absent_comment(
            resource_type="aws.eks.cluster", name=name
        )
        return result
    before = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=resource_id)

    if not before["ret"]:
        result["comment"] = hub.tool.aws.comment_utils.already_absent_comment(
            resource_type="aws.eks.cluster", name=name
        )
    elif ctx.get("test", False):
        result[
            "old_state"
        ] = hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
            raw_resource=before["ret"]["cluster"], idem_resource_name=name
        )
        result["comment"] = hub.tool.aws.comment_utils.would_delete_comment(
            resource_type="aws.eks.cluster", name=name
        )
        return result
    else:
        result[
            "old_state"
        ] = hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
            raw_resource=before["ret"]["cluster"], idem_resource_name=name
        )
        try:
            ret = await hub.exec.boto3.client.eks.delete_cluster(
                ctx,
                name=resource_id,
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                result["result"] = False
                return result
            else:
                waiter_config = hub.tool.aws.waiter_utils.create_waiter_config(
                    default_delay=60,
                    default_max_attempts=40,
                    timeout_config=timeout.get("delete") if timeout else None,
                )
                try:
                    await hub.tool.boto3.client.wait(
                        ctx,
                        "eks",
                        "cluster_deleted",
                        name=resource_id,
                        WaiterConfig=waiter_config,
                    )
                except Exception as e:
                    result["comment"] = result["comment"] + (str(e),)
                    result["result"] = False

            result["comment"] = result[
                "comment"
            ] + hub.tool.aws.comment_utils.delete_comment(
                resource_type="aws.eks.cluster", name=name
            )
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = 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


    Lists the Amazon EKS clusters in your Amazon Web Services account in the specified Region.


    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.eks.cluster
    """

    result = {}
    ret = await hub.exec.boto3.client.eks.list_clusters(ctx)

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

    for name in ret["ret"]["clusters"]:
        describe_ret = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=name)
        if not describe_ret["result"] or not describe_ret["ret"]:
            hub.log.debug(
                f"Could not describe cluster {name}, Error:  {describe_ret['comment']}"
            )
            continue
        cluster = describe_ret["ret"]["cluster"]
        resource_id = cluster["name"]
        resource_translated = (
            hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
                raw_resource=cluster, idem_resource_name=resource_id
            )
        )
        result[resource_id] = {
            "aws.eks.cluster.present": [
                {parameter_key: parameter_value}
                for parameter_key, parameter_value in resource_translated.items()
            ]
        }
    return result


async def search(hub, ctx, name, resource_id: str = None):
    r"""
    Provides details about a specific Cluster as a data-source.

    Args:
        name(Text):
             An Idem name of the EKS cluster resource.

        resource_id(Text, optional):
            AWS EKS cluster name to identify the resource.


    Request Syntax:
        [Idem-state-name]:
          aws.eks.cluster.search:
              - name: 'string'
              - resource_id: 'string'

    Response Syntax:
        The following fields will be returned in the `new_state` of the response.

        - name: 'string'
        - resource_id: 'string'
        - role_arn: 'string'
        - arn: 'string'
        - status: 'string'
        - version: 'string'
        - resources_vpc_config:
            clusterSecurityGroupId: 'string'
            endpointPrivateAccess: boolean
            endpointPublicAccess: boolean
            publicAccessCidrs:
            - 'string'
            securityGroupIds: list
            subnetIds:
            - 'string'
            - 'string'
            vpcId: 'string'
        - kubernetes_network_config:
            ipFamily: 'string'
            serviceIpv4Cidr: 'string'
        - logging:
            clusterLogging:
            - enabled: boolean
              types:
              - 'string'
              - 'string'
              - 'string'
              - 'string'
        - tags:
            'string': 'string'
        - oidc_identity_issuer: 'string'
        - endpoint: 'string'
        - certificate_authority:
            data: 'string'

    Examples:

        Input state file:

        .. code-block:: bash

            idem-test-cluster-search:
                aws.eks.cluster.search:
                  - name: idem-test-cluster-search
                  - resource_id: cluster-1

        Sample response:

            - name: cluster-1
            - resource_id: cluster-1
            - role_arn: arn:aws:iam::598227425989:role/eksClusterRole
            - arn: arn:aws:eks:us-west-2:598227425989:cluster/cluster01
            - status: ACTIVE
            - version: '1.21'
            - resources_vpc_config:
                clusterSecurityGroupId: sg-0e364c2e68739a515
                endpointPrivateAccess: false
                endpointPublicAccess: true
                publicAccessCidrs:
                - 0.0.0.0/0
                securityGroupIds: []
                subnetIds:
                - subnet-0f08315b4e261dd70
                - subnet-0a8bfb7b1298755e0
                vpcId: vpc-06ad93e0c4ccdf8b3
            - kubernetes_network_config:
                ipFamily: ipv4
                serviceIpv4Cidr: 172.20.0.0/16
            - logging:
                clusterLogging:
                - enabled: false
                  types:
                  - api
                  - audit
                  - authenticator
                  - controllerManager
                  - scheduler
            - tags:
                Name: cluster-1
            - oidc_identity_issuer: https://oidc.eks.us-west-2.amazonaws.com/id/4E0FCBD1CFBD5DD3C662D0AED6514340
            - endpoint: https://4E0FCBD1CFBD5DD3C662D0AED6514340.sk1.us-west-2.eks.amazonaws.com
            - certificate_authority:
                data: LS0tLjdExMNgpnQU5GQmtOYk5tUWxoaUkyZmg0dzB2SGVUTlN4MkNnYk5VN29mTEt4cmxNNjhvZ0YyXZUOEQ3TDEvaHhQQW9YMzZ6lyCjBEcDRvb


    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)

    ret = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=resource_id)

    if not ret["result"]:
        result["result"] = False
        result["comment"] = ret["comment"]
        return result

    cluster = ret["ret"].get("cluster")
    translated_resource = (
        hub.tool.aws.eks.conversion_utils.convert_raw_cluster_to_present(
            raw_resource=cluster, idem_resource_name=name
        )
    )

    if cluster.get("identity") and cluster.get("identity").get("oidc"):
        translated_resource["oidc_identity_issuer"] = (
            cluster.get("identity").get("oidc").get("issuer")
        )

    translated_resource["endpoint"] = cluster.get("endpoint")
    translated_resource["certificate_authority"] = cluster.get("certificateAuthority")

    result["old_state"] = translated_resource
    # Populate both "old_state" and "new_state" with the same data
    result["new_state"] = copy.deepcopy(result["old_state"])
    return result
