"""State module for managing EKS Fargate profile."""
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"]


TREQ = {
    "present": {
        "require": [
            "aws.eks.cluster.present",
        ],
    },
}
resource_type = "aws.eks.fargate_profile"


async def present(
    hub,
    ctx,
    name: str,
    cluster_name: str,
    pod_execution_role_arn: str,
    resource_id: str = None,
    subnets: List[str] = None,
    selectors: List[
        make_dataclass(
            "FargateProfileSelector",
            [
                ("namespace", str, field(default=None)),
                ("labels", Dict[str, str], field(default=None)),
            ],
        )
    ] = None,
    client_request_token: str = None,
    tags: Dict[str, str] = None,
    timeout: make_dataclass(
        "Timeout",
        [
            (
                "create",
                make_dataclass(
                    "CreateTimeout",
                    [
                        ("delay", int, field(default=10)),
                        ("max_attempts", int, field(default=60)),
                    ],
                ),
                field(default=None),
            ),
            (
                "update",
                make_dataclass(
                    "UpdateTimeout",
                    [
                        ("delay", int, field(default=10)),
                        ("max_attempts", int, field(default=60)),
                    ],
                ),
                field(default=None),
            ),
        ],
    ) = None,
) -> Dict[str, Any]:
    """Creates an Fargate profile for your Amazon EKS cluster.

    You must have at least one Fargate profile in a cluster to be able to run pods on Fargate. The Fargate profile allows
    an administrator to declare which pods run on Fargate and specify which pods run on which Fargate profile. This
    declaration is done through the profile’s selectors. Each profile can have up to five selectors that contain a
    namespace and labels. A namespace is required for every selector. The label field consists of multiple optional
    key-value pairs. Pods that match the selectors are scheduled on Fargate. If a to-be-scheduled pod matches any of the
    selectors in the Fargate profile, then that pod is run on Fargate. When you create a Fargate profile, you must specify
    a pod execution role to use with the pods that are scheduled with the profile. For more information, see Pod Execution
    Role in the Amazon EKS User Guide. Fargate profiles are immutable. However, you can create a new updated profile to
    replace an existing profile and then delete the original after the updated profile has finished creating. If any
    Fargate profiles in a cluster are in the DELETING status, you must wait for that Fargate profile to finish deleting
    before you can create any other profiles in that cluster. For more information, see Fargate Profile in the Amazon EKS
    User Guide.

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

        cluster_name(str):
            The name of the Amazon EKS cluster to apply the Fargate profile to.

        pod_execution_role_arn(str):
            The Amazon Resource Name (ARN) of the pod execution role to use for pods that match the
            selectors in the Fargate profile.

        subnets(list[str], Optional):
            The IDs of subnets to launch your pods into. At this time, pods running on Fargate are not assigned public
            IP addresses, so only private subnets (with no direct route to an Internet Gateway) are accepted for this
            parameter. Defaults to None. Private subnets selected for fargate profile creation must be in different
            availability zones. Defaults to None.

        selectors(list[dict[str, Any]], Optional):
            The selectors to match for pods to use this Fargate profile. Each selector must have an associated namespace.
            Optionally, you can also specify labels for a namespace. You may specify up to five selectors in a Fargate
            profile. Defaults to None.

            * namespace (str, Optional):
                The Kubernetes namespace that the selector should match.

            * labels (dict[str, str], Optional):
                The Kubernetes labels that the selector should match. A pod must contain all of the labels that are
                specified in the selector for it to be considered a match.

        client_request_token(str, Optional):
            Unique, case-sensitive identifier that you provide to ensure the idempotency of the request. Defaults to None.

        tags(dict, Optional):
            The metadata to apply to the Fargate profile to assist with categorization and organization.
            Each tag consists of a key and an Optional value. Defaults to None.

        resource_id(str, Optional):
            AWS Fargate Profile name

        timeout(dict, Optional):
            Timeout configuration for operations on fargate_profile

            * create (dict) -- Timeout configuration for creating fargate_profile
                * delay -- The amount of time in seconds to wait between attempts.
                * max_attempts -- The maximum number of attempts to be made.

    Request Syntax:
        .. code-block:: sls

            fargate_resource_id:
              aws.eks.fargate_profile.present:
                - name: 'string'
                - resource_id: 'string'
                - cluster_name: 'string'
                - pod_execution_role_arn: 'string'
                - subnets:
                  - private_subnet_id
                  - private_subnet_id
                - selectors:
                  - labels: {}
                    namespace: 'string'
                - tags:
                  - 'string': 'string'

    Returns:
        Dict[str, Any]

    Examples:
        .. code-block:: sls

            fargate01-idem-cluster01:
              aws.eks.fargate_profile.present:
                - name: fargate01
                - cluster_name: idem-cluster01
                - pod_execution_role_arn: arn:aws:iam::537227425989:role/eksfargateprofile-role
                - subnets:
                  - subnet-006a41c410b9485dd
                  - subnet-01368936bb540ba1e
                - selectors:
                  - labels: {}
                    namespace: default
                - tags:
                    fargate01: 'created via code'
    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    before = await hub.exec.boto3.client.eks.describe_fargate_profile(
        ctx,
        clusterName=cluster_name,
        fargateProfileName=resource_id if resource_id else name,
    )

    # existing resource
    if before and before["ret"]["fargateProfile"]:
        result[
            "old_state"
        ] = hub.tool.aws.eks.conversion_utils.convert_raw_fargate_profile_to_present(
            raw_resource=before["ret"]["fargateProfile"]
        )
        result["new_state"] = copy.deepcopy(result["old_state"])
        result["comment"] = (f"aws.eks.fargate_profile '{name}' already exists",)
        # fargate_profile can only be updated for tags after its creation, but tag update apis are currently
        # supported for eks clusters and nodegroups only. So no update operations are performed
        return result
    else:
        if ctx.get("test", False):
            result["new_state"] = hub.tool.aws.test_state_utils.generate_test_state(
                enforced_state={},
                desired_state={
                    "name": name,
                    "cluster_name": cluster_name,
                    "resource_id": resource_id,
                    "client_request_token": client_request_token,
                    "pod_execution_role_arn": pod_execution_role_arn,
                    "tags": tags,
                    "subnets": subnets,
                    "selectors": selectors,
                },
            )
            result["comment"] = hub.tool.aws.comment_utils.would_create_comment(
                resource_type=resource_type, name=name
            )
            return result
        # create a new resource
        ret = await hub.exec.boto3.client.eks.create_fargate_profile(
            ctx,
            fargateProfileName=name,
            clusterName=cluster_name,
            podExecutionRoleArn=pod_execution_role_arn,
            subnets=subnets,
            selectors=selectors,
            clientRequestToken=client_request_token,
            tags=tags,
        )
        result["result"] = ret["result"]
        if not result["result"]:
            result["comment"] = ret["comment"]
            return result

        # create waiter config
        waiter_config = hub.tool.aws.waiter_utils.create_waiter_config(
            default_delay=10,
            default_max_attempts=60,
            timeout_config=timeout.get("create") if timeout else None,
        )
        hub.log.debug(f"Waiting on creating aws.eks.fargate_profile '{name}'")
        try:
            # wait till fargate_profile is active,
            await hub.tool.boto3.client.wait(
                ctx,
                "eks",
                "fargate_profile_active",
                None,
                clusterName=cluster_name,
                fargateProfileName=name,
                WaiterConfig=waiter_config,
            )
        except Exception as e:
            result["comment"] = result["comment"] + (str(e),)
            result["result"] = False

        result["comment"] = hub.tool.aws.comment_utils.create_comment(
            resource_type=resource_type, name=name
        )

    # Get the newly created resource
    result[
        "new_state"
    ] = hub.tool.aws.eks.conversion_utils.convert_raw_fargate_profile_to_present(
        raw_resource=ret["ret"]["fargateProfile"]
    )
    return result


async def absent(
    hub,
    ctx,
    name: str,
    cluster_name: str,
    resource_id: str = None,
    timeout: Dict = None,
) -> Dict[str, Any]:
    """Deletes an Fargate profile.

    When you delete a Fargate profile, any pods running on Fargate that were created with the profile are deleted. If
    those pods match another Fargate profile, then they are scheduled on Fargate with that profile. If they no longer
    match any Fargate profiles, then they are not scheduled on Fargate and they may remain in a pending state. Only one
    Fargate profile in a cluster can be in the DELETING status at a time. You must wait for a Fargate profile to finish
    deleting before you can delete any other profiles in that cluster.

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

        cluster_name(str):
            The name of the Amazon EKS cluster associated with the Fargate profile to delete.

        resource_id(str, Optional):
            AWS Fargate profile name. Idem considers name of fargate profile if
         this field is not specified.

        timeout(dict, Optional):
            Timeout configuration for operations on fargate_profile

            * delete (dict) -- Timeout configuration for deleting fargate_profile
                * delay -- The amount of time in seconds to wait between attempts.
                * max_attempts -- The maximum number of attempts to be made

    Request Syntax:
        .. code-block:: sls

            fargate_resource_id:
              aws.eks.fargate_profile.absent:
                - name: 'string'
                - cluster_name: 'string'
    Returns:
        Dict[str, Any]

    Examples:
        .. code-block:: sls

            fargate01-idem-cluster01:
              aws.eks.fargate_profile.absent:
                - resource_id: fargate01
                - name: fargate01
                - cluster_name: idem-cluster01
    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    before = await hub.exec.boto3.client.eks.describe_fargate_profile(
        ctx,
        clusterName=cluster_name,
        fargateProfileName=resource_id if resource_id else name,
    )
    if before and before["ret"]["fargateProfile"]:
        result[
            "old_state"
        ] = hub.tool.aws.eks.conversion_utils.convert_raw_fargate_profile_to_present(
            raw_resource=before["ret"]["fargateProfile"]
        )

    if not before:
        result["comment"] = hub.tool.aws.comment_utils.already_absent_comment(
            resource_type=resource_type, name=name
        )
    else:
        if ctx.get("test", False):
            result["comment"] = hub.tool.aws.comment_utils.would_delete_comment(
                resource_type=resource_type, name=name
            )
        else:
            ret = await hub.exec.boto3.client.eks.delete_fargate_profile(
                ctx,
                clusterName=cluster_name,
                fargateProfileName=resource_id if resource_id else name,
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result

            # wait till fargate_profile has been deleted
            waiter_config = hub.tool.aws.waiter_utils.create_waiter_config(
                default_delay=30,
                default_max_attempts=60,
                timeout_config=timeout.get("delete") if timeout else None,
            )
            hub.log.debug(f"Waiting on deleting aws.eks.fargate_profile '{name}'")
            try:
                await hub.tool.boto3.client.wait(
                    ctx,
                    "eks",
                    "fargate_profile_deleted",
                    None,
                    fargateProfileName=resource_id,
                    clusterName=cluster_name,
                    WaiterConfig=waiter_config,
                )
            except Exception as e:
                result["comment"] = result["comment"] + (str(e),)
                result["result"] = False
            result["comment"] = hub.tool.aws.comment_utils.delete_comment(
                resource_type=resource_type, name=name
            )
    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.

    Lists the Fargate profiles associated with the specified cluster in your Amazon Web Services account in the
    specified Region.

    Returns:
        Dict[str, Dict[str, Any]]

    Examples:
        .. code-block:: bash

            $ idem describe aws.eks.fargate_profile

    """

    result = {}
    # List all clusters
    cluster_ret = await hub.exec.boto3.client.eks.list_clusters(ctx)
    if not cluster_ret["result"]:
        hub.log.debug(f"Could not list clusters {cluster_ret['comment']}")
        return {}

    fargate_profile_list = []
    # Get fargate profiles in each cluster
    for clusterName in cluster_ret["ret"]["clusters"]:
        fargate_profiles_ret = await hub.exec.boto3.client.eks.list_fargate_profiles(
            ctx, clusterName=clusterName
        )
        if not fargate_profiles_ret["result"]:
            hub.log.info(
                f"No fargate profiles could be listed for cluster {clusterName}. Fetching the next cluster."
            )
            continue

        # maintain a list of clusterName and fargateProfileName for future use
        for fargate_profile_name in fargate_profiles_ret["ret"]["fargateProfileNames"]:
            fargate_profile_list.append(
                {
                    "clusterName": clusterName,
                    "fargateProfileName": fargate_profile_name,
                }
            )
    # Describe each fargate profile
    for fargate_profile in fargate_profile_list:
        clusterName = fargate_profile["clusterName"]
        fargateProfileName = fargate_profile["fargateProfileName"]
        describe_ret = await hub.exec.boto3.client.eks.describe_fargate_profile(
            ctx, clusterName=clusterName, fargateProfileName=fargateProfileName
        )

        if not describe_ret["result"]:
            hub.log.info(
                f"Describe command failed for resource {fargateProfileName} under cluster {clusterName}"
            )
            continue

        fargate_profile = describe_ret["ret"]["fargateProfile"]
        translated_resource = (
            hub.tool.aws.eks.conversion_utils.convert_raw_fargate_profile_to_present(
                raw_resource=fargate_profile
            )
        )
        # state_id is combination of fargateProfileName and clusterName to maintain integrity as more than one
        # cluster can have same fargate profile names
        state_id = (
            fargate_profile.get("fargateProfileName")
            + "-"
            + fargate_profile.get("clusterName")
        )
        result[state_id] = {
            "aws.eks.fargate_profile.present": [
                {parameter_key: parameter_value}
                for parameter_key, parameter_value in translated_resource.items()
            ]
        }

    return result
