"""
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
import time
from collections import OrderedDict
from typing import Any
from typing import Dict

from dict_tools import differ

__contracts__ = ["resource"]

TREQ = {
    "absent": {
        "require": [
            "aws.ec2.subnet.absent",
            "aws.iam.role.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,
    version: str = None,
    resources_vpc_config: Dict = None,
    kubernetes_network_config: Dict = None,
    logging: Dict = None,
    encryption_config: Dict = None,
    tags: Dict[str, str] = 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): A name, ID to identify the 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, required): 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.
        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.

    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'
              - 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:
                  one: '1'
                  two: '2'

    """

    result = dict(comment="", old_state=None, new_state=None, name=name, result=True)
    is_changed = False
    before = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=name)
    if ctx.get("test", False):
        if before:
            result["comment"] = f"Would update aws.eks.cluster {name}"
            result["result"] = True
        else:
            result["comment"] = f"Would create aws.eks.cluster {name}"
            result["result"] = True
        return result

    try:
        if before:
            result["comment"] = f"'{name}' already exists"
            result["old_state"] = before["ret"]["cluster"]
            arn = before["ret"]["cluster"]["arn"]
            if before["ret"]["cluster"].get("clientRequestToken"):
                client_request_token = before["ret"]["cluster"]["clientRequestToken"]
            else:
                client_request_token = None
            # change depends on resourcesVpcConfig,  encryptionConfig, logging and version
            if version and before["ret"]["cluster"].get("version") != version:
                ret = await hub.exec.boto3.client.eks.update_cluster_version(
                    ctx,
                    name=name,
                    version=version,
                    clientRequestToken=client_request_token,
                )
                result["result"] = ret["result"]
                if not result["result"]:
                    result["comment"] = ret["comment"]
                    return result
                time.sleep(60)
                await hub.tool.boto3.client.wait(
                    ctx,
                    "eks",
                    "cluster_active",
                    None,
                    name=name,
                    WaiterConfig={"MaxAttempts": update_attempts},
                )
                is_changed = True

            if (
                encryption_config
                and before["ret"]["cluster"].get("encryptionConfig")
                != encryption_config
            ):
                ret = await hub.exec.boto3.client.eks.associate_encryption_config(
                    ctx,
                    clusterName=name,
                    encryptionConfig=encryption_config,
                    clientRequestToken=client_request_token,
                )
                result["result"] = ret["result"]
                if not result["result"]:
                    result["comment"] = ret["comment"]
                    return result
                await hub.tool.boto3.client.wait(
                    ctx,
                    "eks",
                    "cluster_active",
                    None,
                    name=name,
                    WaiterConfig={"MaxAttempts": update_attempts},
                )
                is_changed = True

            if logging:
                if differ.deep_diff(before["ret"]["cluster"].get("logging"), logging):
                    ret = await hub.exec.boto3.client.eks.update_cluster_config(
                        ctx,
                        name=name,
                        logging=logging,
                        clientRequestToken=client_request_token,
                    )
                    result["result"] = ret["result"]
                    if not result["result"]:
                        result["comment"] = ret["comment"]
                        return result
                    await hub.tool.boto3.client.wait(
                        ctx,
                        "eks",
                        "cluster_active",
                        None,
                        name=name,
                        WaiterConfig={"MaxAttempts": update_attempts},
                    )
                    time.sleep(60)
                    is_changed = True
            vpc_config_changes = hub.tool.aws.eks_utils.get_resource_vpc_config_changes(
                resources_vpc_config,
                before["ret"]["cluster"].get("resourcesVpcConfig"),
            )
            if vpc_config_changes:
                ret = await hub.exec.boto3.client.eks.update_cluster_config(
                    ctx,
                    name=name,
                    resourcesVpcConfig=vpc_config_changes,
                    clientRequestToken=client_request_token,
                )
                result["result"] = ret["result"]
                if not result["result"]:
                    result["comment"] = ret["comment"]
                    return result
                await hub.tool.boto3.client.wait(
                    ctx,
                    "eks",
                    "cluster_active",
                    None,
                    name=name,
                    WaiterConfig={"MaxAttempts": update_attempts},
                )
                is_changed = True
            # update tags
            old_tags = (
                copy.deepcopy(before["ret"]["cluster"].get("tags"))
                if before["ret"]["cluster"].get("tags")
                else {}
            )

            update_tags_ret = await hub.exec.aws.eks.tag.update_eks_tags(
                ctx=ctx,
                resource_arn=arn,
                old_tags=old_tags,
                new_tags=tags,
            )
            if not update_tags_ret["result"]:
                result["comment"] = update_tags_ret["comment"]
                result["result"] = False
                return result
            if update_tags_ret["ret"]:
                is_changed = True
            if is_changed:
                result["comment"] = f"Updated '{name}'"
        else:
            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
                await hub.tool.boto3.client.wait(
                    ctx,
                    "eks",
                    "cluster_active",
                    None,
                    name=name,
                    WaiterConfig={"MaxAttempts": create_attempts},
                )
                is_changed = True
                result["comment"] = f"Created '{name}'"
            except hub.tool.boto3.exception.ClientError as e:
                result["comment"] = f"{e.__class__.__name__}: {e}"
                result["result"] = False
    except Exception as e1:
        result["comment"] = f"{e1.__class__.__name__}: {e1}"
        result["result"] = False
        return result

    try:
        if is_changed:
            after = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=name)
            result["new_state"] = after["ret"]["cluster"]
        else:
            result["new_state"] = copy.deepcopy(result["old_state"])
    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 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): A name, ID to identify the resource.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            my_cluster:
              aws.eks.cluster.absent:
                - role_arn: arn:aws:iam::202236654445:role/ek1
                - version: '1.21'
    """

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

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

    if not before:
        result["comment"] = f"'{name}' already absent"
    elif ctx.get("test", False):
        result["comment"] = f"Would delete aws.eks.cluster {name}"
        return result
    else:
        result["old_state"] = before["ret"]["cluster"]
        try:
            ret = await hub.exec.boto3.client.eks.delete_cluster(
                ctx,
                name=name,
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                result["result"] = False
                return result
            await hub.tool.boto3.client.wait(
                ctx,
                "eks",
                "cluster_deleted",
                None,
                name=name,
            )
            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


    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 describe cluster {ret['comment']}")
        return {}
    describe_parameters = OrderedDict(
        {
            "roleArn": "role_arn",
            "status": "status",
            "version": "version",
            "endpoint": "endpoint",
        }
    )

    for name in ret["ret"]["clusters"]:
        describe_ret = await hub.exec.boto3.client.eks.describe_cluster(ctx, name=name)
        cluster = describe_ret["ret"]["cluster"]
        new_cluster = []
        for parameter_old_key, parameter_new_key in describe_parameters.items():
            if cluster.get(parameter_old_key) is not None:
                new_cluster.append({parameter_new_key: cluster.get(parameter_old_key)})
        if cluster.get("resourcesVpcConfig"):
            resources_vpc_config = cluster.get("resourcesVpcConfig").copy()
            resources_vpc_config.pop("vpcId", None)
            new_cluster.append({"resources_vpc_config": resources_vpc_config})
        if cluster.get("kubernetesNetworkConfig"):
            new_cluster.append(
                {
                    "kubernetes_network_config": cluster.get(
                        "kubernetesNetworkConfig"
                    ).copy()
                }
            )
        if cluster.get("logging"):
            new_cluster.append({"logging": cluster.get("logging").copy()})
        if cluster.get("encryptionConfig"):
            new_cluster.append(
                {"encryption_config": cluster.get("encryptionConfig").copy()}
            )
        if cluster.get("certificateAuthority"):
            new_cluster.append(
                {"certificate_authority": cluster.get("certificateAuthority").copy()}
            )
        if cluster.get("tags"):
            new_cluster.append({"tags": cluster.get("tags").copy()})
        result[name] = {"aws.eks.cluster.present": new_cluster}
    return result
