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

hub.exec.boto3.client.logs.describe_log_groups
hub.exec.boto3.client.logs.create_log_group
hub.exec.boto3.client.logs.delete_log_group
"""
import copy
from typing import Any
from typing import Dict


__contracts__ = ["resource"]


async def present(
    hub,
    ctx,
    name: str,
    resource_id: str = None,
    kms_key_id: str = None,
    tags: dict = None,
) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Creates a log group if it does not already exist. You can create up to 5000 log groups per account.
    You must use the following guidelines when naming a log group:
        - Log group names must be unique within a region for an AWS account.
        - Log group names can be between 1 and 512 characters long.
        - Log group names consist of the following characters: a-z, A-Z, 0-9, '_' (underscore), '-' (hyphen), '/' (forward slash), and '.' (period).
    If you associate a AWS Key Management Service (AWS KMS) customer master key (CMK) with the log group, ingested data is encrypted using the CMK.
    This association is stored as long as the data encrypted with the CMK is still within Amazon CloudWatch Logs. This enables Amazon CloudWatch Logs
    to decrypt this data whenever it is requested.
    If you attempt to associate a CMK with the log group but the CMK does not exist or the CMK is disabled, you will receive an InvalidParameterException error.

    Args:
        name(Text): An Idem name of the resource.
        resource_id(Text, optional): AWS Cloudwatch log group ID
        kms_key_id(Text, optional): The Amazon Resource Name (ARN) of the CMK to use when encrypting log data.
        tags(dict, optional): The key-value pairs to use for the tags.

    Request Syntax:
        [log_group_name]:
          aws.cloudwatch.log_group.present:
          - name: 'string'
          - kms_key_id: 'string'
          - tags:
            - 'string': 'string'

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws.cloudwatch.log_group.present:
                - name: value
                - tags:
                     TestKey4: TestValue4
                - kms_key_id: "arn:aws:kms:us-east-1:xxxxxxxxx:key/xxxx-9500-xxxxx"
    """

    result = dict(comment="", name=name, old_state=None, new_state=None, result=True)
    before = None
    resource_updated = False
    if resource_id:
        before = await hub.exec.boto3.client.logs.describe_log_groups(
            ctx, logGroupNamePrefix=resource_id
        )
    try:
        if before and before["ret"]["logGroups"]:
            result[
                "old_state"
            ] = await hub.tool.aws.cloudwatch.conversion_utils.convert_raw_log_group_to_present(
                ctx, raw_resource=before["ret"]["logGroups"][0], idem_resource_name=name
            )
            plan_state = copy.deepcopy(result["old_state"])
            result["comment"] = f"'{name}' already present."
            if tags is not None and dict(result["old_state"].get("tags")) != tags:
                update_ret = await hub.exec.aws.cloudwatch.tag.update_tags(
                    ctx=ctx,
                    resource_name=resource_id,
                    old_tags=result["old_state"].get("tags"),
                    new_tags=tags,
                )
                result["comment"] = f"{result['comment']} . {update_ret['comment']}"
                result["result"] = update_ret["result"]
                resource_updated = resource_updated or bool(update_ret["ret"])
                if ctx.get("test", False) and update_ret["ret"] is not None:
                    plan_state["tags"] = update_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,
                        "kms_key_id": kms_key_id,
                        "tags": tags,
                    },
                )
                result["comment"] = f"Would create aws.cloudwatch.log_group {name}"
                return result
            ret = await hub.exec.boto3.client.logs.create_log_group(
                ctx, logGroupName=name, kmsKeyId=kms_key_id, tags=tags
            )
            resource_id = name
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            ret["comment"] = f"Created '{name}'"
    except hub.tool.boto3.exception.ClientError as e:
        result["result"] = False
        result["comment"] = f"{e.__class__.__name__}: {e}"
    try:
        if ctx.get("test", False):
            result["new_state"] = plan_state
        elif (not before) or resource_updated:
            after = await hub.exec.boto3.client.logs.describe_log_groups(
                ctx, logGroupNamePrefix=resource_id
            )
            result[
                "new_state"
            ] = await hub.tool.aws.cloudwatch.conversion_utils.convert_raw_log_group_to_present(
                ctx, raw_resource=after["ret"]["logGroups"][0], idem_resource_name=name
            )
        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, resource_id: str) -> Dict[str, Any]:
    r"""
    **Autogenerated function**

    Deletes the specified cloudwatch log group.

    Args:
        name(Text): The log Group name.
        resource_id(Text): The AWS ID of the log group

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws.cloudwatch.log_group.absent:
                - name: value
    """

    result = dict(comment="", name=name, old_state=None, new_state=None, result=True)
    before = await hub.exec.boto3.client.logs.describe_log_groups(
        ctx, logGroupNamePrefix=resource_id
    )
    if not before["ret"]["logGroups"]:
        result["comment"] = f"'{name}' already absent"
        return result
    else:
        result[
            "old_state"
        ] = await hub.tool.aws.cloudwatch.conversion_utils.convert_raw_log_group_to_present(
            ctx, raw_resource=before["ret"]["logGroups"][0], idem_resource_name=name
        )
        if ctx.get("test", False):
            result["comment"] = f"Would delete aws.cloudwatch.log_group {name}"
            return result
        try:
            ret = await hub.exec.boto3.client.logs.delete_log_group(
                ctx, logGroupName=resource_id
            )
            result["result"] = ret["result"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            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


    Returns a list of cloudwatch log group descriptions. If a log group name is specified, the list contains only
    the description of that group.


    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.cloudwatch.log_group
    """
    result = {}
    ret = await hub.exec.boto3.client.logs.describe_log_groups(ctx)
    if not ret["result"]:
        hub.log.debug(f"Could not describe log groups {ret['comment']}")
        return {}

    for resource in ret["ret"]["logGroups"]:
        resource_id = resource.get("logGroupName")
        resource_translated = await hub.tool.aws.cloudwatch.conversion_utils.convert_raw_log_group_to_present(
            ctx, raw_resource=resource, idem_resource_name=resource_id
        )
        result[resource_id] = {
            "aws.cloudwatch.log_group.present": [
                {parameter_key: parameter_value}
                for parameter_key, parameter_value in resource_translated.items()
            ]
        }
    return result
