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

hub.exec.boto3.client.dynamodb.create_table
hub.exec.boto3.client.dynamodb.delete_table
hub.exec.boto3.client.dynamodb.describe_table
hub.exec.boto3.client.dynamodb.list_tables
hub.exec.boto3.client.dynamodb.update_table
resource = hub.tool.boto3.resource.create(ctx, "dynamodb", "Table", name)
hub.tool.boto3.resource.exec(resource, delete, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, delete_item, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, get_item, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, put_item, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, query, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, scan, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, update, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, update_item, *args, **kwargs)
"""
import copy
from dataclasses import field
from dataclasses import make_dataclass
from typing import Any
from typing import Dict
from typing import List


async def present(
    hub,
    ctx,
    name: str,
    attribute_definitions: List[
        make_dataclass(
            "AttributeDefinition", [("AttributeName", str), ("AttributeType", str)]
        )
    ],
    key_schema: List[
        make_dataclass("KeySchemaElement", [("AttributeName", str), ("KeyType", str)])
    ],
    resource_id: str = None,
    billing_mode: str = None,
    sse_specification: make_dataclass(
        "SSESpecification",
        [
            ("Enabled", bool, field(default=None)),
            ("SSEType", str, field(default=None)),
            ("KMSMasterKeyId", str, field(default=None)),
        ],
    ) = None,
    stream_specification: make_dataclass(
        "StreamSpecification",
        [("StreamEnabled", bool), ("StreamViewType", str, field(default=None))],
    ) = None,
    provisioned_throughput: make_dataclass(
        "ProvisionedThroughput",
        [("ReadCapacityUnits", int), ("WriteCapacityUnits", int)],
    ) = None,
    local_secondary_indexes: List[
        make_dataclass(
            "LocalSecondaryIndex",
            [
                ("IndexName", str),
                (
                    "KeySchemaElement",
                    List[
                        make_dataclass(
                            "KeySchema", [("AttributeName", str), ("KeyType", str)]
                        )
                    ],
                ),
                (
                    "Projection",
                    make_dataclass(
                        "Projection",
                        [
                            ("ProjectionType", str, field(default=None)),
                            ("NonKeyAttributes", List[str], field(default=None)),
                        ],
                    ),
                ),
            ],
        )
    ] = None,
    global_secondary_indexes: List[
        make_dataclass(
            "GlobalSecondaryIndex",
            [
                ("IndexName", str),
                (
                    "KeySchemaElement",
                    List[
                        make_dataclass(
                            "KeySchema", [("AttributeName", str), ("KeyType", str)]
                        )
                    ],
                ),
                (
                    "Projection",
                    make_dataclass(
                        "Projection",
                        [
                            ("ProjectionType", str, field(default=None)),
                            ("NonKeyAttributes", List[str], field(default=None)),
                        ],
                    ),
                ),
                (
                    "ProvisionedThroughput",
                    make_dataclass(
                        "ProvisionedThroughput",
                        [("ReadCapacityUnits", int), ("WriteCapacityUnits", int)],
                    ),
                    field(default=None),
                ),
            ],
        )
    ] = None,
    replica_updates: List = None,
    tags: Dict[str, Any]
    or List[
        make_dataclass(
            "Tag",
            [("Key", str, field(default=None)), ("Value", str, field(default=None))],
        )
    ] = None,
    table_class: str = 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**

    The CreateTable operation adds a new table to your account. In an Amazon Web Services account, table names must
    be unique within each Region. That is, you can have two tables with same name if you create the tables in
    different Regions.  CreateTable is an asynchronous operation. Upon receiving a CreateTable request, DynamoDB
    immediately returns a response with a TableStatus of CREATING. After the table is created, DynamoDB sets the
    TableStatus to ACTIVE. You can perform read and write operations only on an ACTIVE table.  You can optionally
    define secondary indexes on the new table, as part of the CreateTable operation. If you want to create multiple
    tables with secondary indexes on them, you must create the tables sequentially. Only one table with secondary
    indexes can be in the CREATING state at any given time. You can use the DescribeTable action to check the table
    status.

    Args:
        name(Text): A name of the table to create.
        resource_id(Text, optional): AWS DynamoDB table name.
        key_schema(List[Dict[str, Any]]): Specifies the attributes that make up the primary key for a table or an index. The attributes in
            KeySchema must also be defined in the AttributeDefinitions array. For more information, see Data
            Model in the Amazon DynamoDB Developer Guide.
            Each KeySchemaElement in the array is composed of:
                AttributeName - The name of this key attribute.
                KeyType - The role that the key attribute will assume:
                    HASH - partition key
                    RANGE - sort key
            The partition key of an item is also known as its hash attribute. The term "hash attribute" derives from the DynamoDB usage of
            an internal hash function to evenly distribute data items across partitions, based on their
            partition key values. The sort key of an item is also known as its range attribute. The term
            "range attribute" derives from the way DynamoDB stores items with the same partition key
            physically close together, in sorted order by the sort key value.  For a simple primary key
            (partition key), you must provide exactly one element with a KeyType of HASH. For a composite
            primary key (partition key and sort key), you must provide exactly two elements, in this order:
            The first element must have a KeyType of HASH, and the second element must have a KeyType of
            RANGE. For more information, see Working with Tables in the Amazon DynamoDB Developer Guide.
            * AttributeName (str): The name of a key attribute.
            * KeyType (str): The role that this key attribute will assume:
                    HASH - partition key
                    RANGE - sort key
                The partition key of an item is also known as its hash attribute. The term "hash attribute" derives
                from DynamoDB's usage of an internal hash function to evenly distribute data items across
                partitions, based on their partition key values. The sort key of an item is also known as its
                range attribute. The term "range attribute" derives from the way DynamoDB stores items with the
                same partition key physically close together, in sorted order by the sort key value.
        attribute_definitions(List[Dict[str, Any]]): An array of attributes that describe the key schema for the table and indexes.
            * AttributeName (str): A name for the attribute.
            * AttributeType (str): The data type for the attribute, where:
                S - the attribute is of type String
                N - the attribute is of type Number
                B - the attribute is of type Binary
        replica_updates: A list of replica update actions (create, delete, or update) for the table.
        table_class(Text, optional): The table class of the new table. Valid values are STANDARD and
                STANDARD_INFREQUENT_ACCESS.
        billing_mode(Text, optional): Controls how users are charged for read and write throughput and how they manage
            capacity.
                PROVISIONED - AWS recommends using PROVISIONED for predictable workloads. PROVISIONED sets the billing
                            mode to Provisioned Mode.
                PAY_PER_REQUEST - AWS recommends using PAY_PER_REQUEST for unpredictable workloads. PAY_PER_REQUEST
                            sets the billing mode to On-Demand Mode .
        global_secondary_indexes(List, optional): One or more global secondary indexes (the maximum is 20) to be created on the table.
            * IndexName (str): The name of the global secondary index. The name must be unique among all other indexes on this
                table.
            * KeySchema (List[Dict[str, Any]]): The complete key schema for a global secondary index
                * AttributeName (str): The name of a key attribute.
                * KeyType (str): The role that this key attribute will assume:
                        HASH - partition key
                        RANGE - sort key
                    The partition key of an item is also known as its hash attribute. The term "hash attribute" derives
                    from DynamoDB's usage of an internal hash function to evenly distribute data items across
                    partitions, based on their partition key values. The sort key of an item is also known as its
                    range attribute. The term "range attribute" derives from the way DynamoDB stores items with the
                    same partition key physically close together, in sorted order by the sort key value.
            * Projection (Dict[str, Any]): Represents attributes that are copied (projected) from the table into the global secondary
                index. These are in addition to the primary key attributes and index key attributes, which are
                automatically projected.
                * ProjectionType (str, optional): The set of attributes that are projected into the index:
                        KEYS_ONLY - Only the index and primary keys are projected into the index.
                        INCLUDE - In addition to the attributes described in KEYS_ONLY, the secondary index will include other non-key attributes that you specify.
                        ALL - All of the table attributes are projected into the index.
            * ProvisionedThroughput (Dict[str, Any], optional): Represents the provisioned throughput settings for the specified global secondary index. For
                current minimum and maximum provisioned throughput values, see Service, Account, and Table
                Quotas in the Amazon DynamoDB Developer Guide.
                * ReadCapacityUnits (int): The maximum number of strongly consistent reads consumed per second before DynamoDB returns a
                    ThrottlingException. For more information, see Specifying Read and Write Requirements in the
                    Amazon DynamoDB Developer Guide. If read/write capacity mode is PAY_PER_REQUEST the value is set
                    to 0.
                * WriteCapacityUnits (int): The maximum number of writes consumed per second before DynamoDB returns a ThrottlingException.
                    For more information, see Specifying Read and Write Requirements in the Amazon DynamoDB
                    Developer Guide. If read/write capacity mode is PAY_PER_REQUEST the value is set to 0.
        local_secondary_indexes(List[Dict[str, Any]], optional): One or more local secondary indexes (the maximum is 5) to be created on the table. Each index is
            scoped to a given partition key value. There is a 10 GB size limit per partition key value;
            otherwise, the size of a local secondary index is unconstrained.
            * IndexName (str): The name of the local secondary index. The name must be unique among all other indexes on this
                table.
            * KeySchema (List[Dict[str, Any]]): The complete key schema for the local secondary index.
                * AttributeName (str): The name of a key attribute.
                * KeyType (str): The role that this key attribute will assume:
                        HASH - partition key
                        RANGE - sort key
                    The partition key of an item is also known as its hash attribute. The term "hash attribute" derives
                    from DynamoDB's usage of an internal hash function to evenly distribute data items across
                    partitions, based on their partition key values. The sort key of an item is also known as its
                    range attribute. The term "range attribute" derives from the way DynamoDB stores items with the
                    same partition key physically close together, in sorted order by the sort key value.
            * Projection (Dict[str, Any]): Represents attributes that are copied (projected) from the table into the local secondary index.
                These are in addition to the primary key attributes and index key attributes, which are
                automatically projected.
                * ProjectionType (str, optional): The set of attributes that are projected into the index:
                        KEYS_ONLY - Only the index and primary keys are projected into the index.
                        INCLUDE - In addition to the attributes described in KEYS_ONLY, the secondary index will include other non-key attributes that you specify.
                        ALL - All of the table attributes are projected into the index.
                * NonKeyAttributes (List[str], optional): Represents the non-key attribute names which will be projected into the index. For local
                    secondary indexes, the total count of NonKeyAttributes summed across all of the local secondary
                    indexes, must not exceed 100. If you project the same attribute into two different indexes, this
                    counts as two distinct attributes when determining the total.
        provisioned_throughput(Dict, optional): Represents the provisioned throughput settings for a specified table or index. The settings can
            be modified using the UpdateTable operation.  If you set BillingMode as PROVISIONED, you must
            specify this property. If you set BillingMode as PAY_PER_REQUEST, you cannot specify this
            property. For current minimum and maximum provisioned throughput values, see Service, Account,
            and Table Quotas in the Amazon DynamoDB Developer Guide. Defaults to None.
            * (ReadCapacityUnits): The maximum number of strongly consistent reads consumed per second before DynamoDB returns a
                ThrottlingException. For more information, see Specifying Read and Write Requirements in the
                Amazon DynamoDB Developer Guide. If read/write capacity mode is PAY_PER_REQUEST the value is set
                to 0.
            * (WriteCapacityUnits): The maximum number of writes consumed per second before DynamoDB returns a ThrottlingException.
                For more information, see Specifying Read and Write Requirements in the Amazon DynamoDB
                Developer Guide. If read/write capacity mode is PAY_PER_REQUEST the value is set to 0.
        stream_specification(Dict[str, Any], optional): The settings for DynamoDB Streams on the table. These settings consist of:
            StreamEnabled - Indicates whether DynamoDB Streams is to be enabled (true) or disabled (false).
            StreamViewType - When an item in the table is modified, StreamViewType determines what
                information is written to the table's stream. Valid values for StreamViewType are:
                    KEYS_ONLY - Only the key attributes of the modified item are written to the stream.
                    NEW_IMAGE - The entire item, as it appears after it was modified, is written to the stream.
                    OLD_IMAGE - The entire item, as it appeared before it was modified, is written to the stream.
                    NEW_AND_OLD_IMAGES - Both the new and the old item images of the item are written to the stream. Defaults to None.
            * StreamEnabled (bool): Indicates whether DynamoDB Streams is enabled (true) or disabled (false) on the table.
            * StreamViewType (str, optional):  When an item in the table is modified, StreamViewType determines what information is written to
                the stream for this table. Valid values for StreamViewType are:
                    KEYS_ONLY - Only the key attributes of the modified item are written to the stream.
                    NEW_IMAGE - The entire item, as it appears after it was modified, is written to the stream.
                    OLD_IMAGE - The entire item, as it appeared before it was modified, is written to the stream.
                    NEW_AND_OLD_IMAGES - Both the new and the old item images of the item are written to the stream.
        sse_specification(Dict[str, Any], optional): Represents the settings used to enable server-side encryption. Defaults to None.
            * Enabled (bool, optional): Indicates whether server-side encryption is done using an Amazon Web Services managed key or an
                Amazon Web Services owned key. If enabled (true), server-side encryption type is set to KMS and
                an Amazon Web Services managed key is used (KMS charges apply). If disabled (false) or not
                specified, server-side encryption is set to Amazon Web Services owned key.
            * SSEType (str, optional): Server-side encryption type.
                The only supported value is:
                    KMS - Server-side encryption that uses Key Management Service. The key is stored in your account
                        and is managed by KMS (KMS charges apply).
            * KMSMasterKeyId (str, optional): The KMS key that should be used for the KMS encryption. To specify a key, use its key ID, Amazon
                Resource Name (ARN), alias name, or alias ARN. Note that you should only provide this parameter
                if the key is different from the default DynamoDB key alias/aws/dynamodb.
        tags(List or Dict, optional): The tags to assign to the route_table. Defaults to None. Format can be [{"Key": tag-key, "Value": tag-value}] or dict {tag-key: tag-value}
            * Key (str): The key of the tag. Tag keys are case sensitive. Each DynamoDB table can only have up to one tag
                with the same key. If you try to add an existing tag (same key), the existing tag value will be
                updated to the new value.
            * Value (str): The value of the tag. Tag values are case-sensitive and can be null.
        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:
        [dynamodb_table-name]:
          aws.dynamodb.table.present:
          - name: 'string'
          - attribute_definitions: 'list'
          - key_schema: 'list'
          - resource_id: 'string'
          - billing_mode: 'string'
          - sse_specification: 'dict'
          - stream_specification: 'dict'
          - provisioned_throughput: 'dict'
          - local_secondary_indexes: 'list'
          - global_secondary_indexes: 'list'
          - tags:
            - Key: 'string'
              Value: 'string'
          - table_class: 'str'

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            test_dyanmodb_table:
              aws.dynamodb.table.present:
                - name: test_dyanmodb_table
                - resource_id: dyanmodb_table-1e8965drf2c56902g
                - attribute_definitions:
                  - AttributeName: Artist
                    AttributeType: S
                  - AttributeName: SongTitle
                    AttributeType: S
                - key_schema:
                  - AttributeName: Artist
                    AttributeType: HASH
                  - AttributeName: SongTitle
                    AttributeType: RANGE
                - provisioned_throughput = { "ReadCapacityUnits": 123, "WriteCapacityUnits": 123, }
                - tags:
                  - Key: Name
                    Value: test-nat-gateway
    """

    result = dict(comment=(), old_state=None, new_state=None, name=name, result=True)
    is_table_updated = False
    existing_tags = None
    before = None
    plan_state = {}
    are_tags_updated = False
    table_arn = None
    if resource_id:
        before = await hub.exec.boto3.client.dynamodb.describe_table(
            ctx, TableName=resource_id
        )
    if isinstance(tags, List):
        tags = hub.tool.aws.tag_utils.convert_tag_list_to_dict(tags)

    if before and before["result"]:
        result["comment"] = (f"aws.dynamodb.table '{name}' is already present",)
        table_resource = before["ret"].get("Table")
        table_arn = table_resource.get("TableArn")
        tags_ret = await hub.exec.boto3.client.dynamodb.list_tags_of_resource(
            ctx, ResourceArn=table_arn
        )
        result["result"] = tags_ret.get("result")
        if result["result"]:
            existing_tags = tags_ret.get("ret").get("Tags")
        else:
            result["comment"] = result["comment"] + (tags_ret["comment"],)
            return result
        result[
            "old_state"
        ] = hub.tool.aws.dynamodb.conversion_utils.convert_raw_dynamodb_table_to_present(
            raw_resource=before["ret"].get("Table"),
            idem_resource_name=name,
            tags=existing_tags,
        )
        plan_state = copy.deepcopy(result["old_state"])
        update_ret = (
            await hub.exec.aws.dynamodb.table.compare_inputs_and_update_dynamodb_table(
                ctx=ctx,
                plan_state=plan_state,
                attribute_definitions=attribute_definitions,
                name=name,
                billing_mode=billing_mode,
                provisioned_throughput=provisioned_throughput,
                global_secondary_indexes=global_secondary_indexes,
                sse_specification=sse_specification,
                stream_specification=stream_specification,
                replica_updates=replica_updates,
                table_class=table_class,
                timeout=timeout,
            )
        )
        result["result"] = result["result"] and update_ret["result"]
        result["comment"] = result["comment"] + update_ret["comment"]
        if result["result"]:
            is_table_updated = True
        if tags is not None and tags != result["old_state"].get("tags"):
            # Update tags
            update_tags_result = await hub.exec.aws.dynamodb.tag.update_tags(
                ctx=ctx,
                resource_arn=table_arn,
                old_tags=hub.tool.aws.tag_utils.convert_tag_list_to_dict(existing_tags)
                if existing_tags
                else {},
                new_tags=tags,
            )
            result["comment"] = result["comment"] + update_tags_result["comment"]
            result["result"] = result["result"] and update_tags_result["result"]

            if not result["result"]:
                return result
            are_tags_updated = result["result"]

            if ctx.get("test", False) and (update_tags_result["ret"] is not None):
                plan_state["tags"] = update_tags_result["ret"]
    else:
        if ctx.get("test", False):
            result["new_state"] = hub.tool.aws.test_state_utils.generate_test_state(
                enforced_state={},
                desired_state={
                    "attribute_definitions": attribute_definitions,
                    "key_schema": key_schema,
                    "name": name,
                    "stream_specification": stream_specification,
                    "billing_mode": billing_mode,
                    "table_class": table_class,
                    "local_secondary_indexes": local_secondary_indexes,
                    "global_secondary_indexes": global_secondary_indexes,
                    "sse_specification": sse_specification,
                    "provisioned_throughput": provisioned_throughput,
                    "replica_updates": replica_updates,
                    "tags": tags,
                    "resource_id": name,
                },
            )
            result["comment"] = hub.tool.aws.comment_utils.would_create_comment(
                resource_type="aws.dynamodb.table", name=name
            )
            return result
        try:
            ret = await hub.exec.boto3.client.dynamodb.create_table(
                ctx,
                AttributeDefinitions=attribute_definitions,
                KeySchema=key_schema,
                TableName=name,
                BillingMode=billing_mode,
                GlobalSecondaryIndexes=global_secondary_indexes,
                LocalSecondaryIndexes=local_secondary_indexes,
                ProvisionedThroughput=provisioned_throughput,
                SSESpecification=sse_specification,
                StreamSpecification=stream_specification,
                Tags=hub.tool.aws.tag_utils.convert_tag_dict_to_list(tags)
                if tags is not None
                else None,
                TableClass=table_class,
            )
            result["result"] = ret["result"]
            if not ret["result"]:
                result["comment"] = ret["comment"]
                return result
            waiter_config = hub.tool.aws.waiter_utils.create_waiter_config(
                default_delay=15,
                default_max_attempts=40,
                timeout_config=timeout.get("create") if timeout else None,
            )
            hub.log.debug(f"Waiting on creating aws.dynamodb.table '{name}'")
            try:
                await hub.tool.boto3.client.wait(
                    ctx,
                    "dynamodb",
                    "table_exists",
                    TableName=name,
                    WaiterConfig=waiter_config,
                )
            except Exception as e:
                result["comment"] = result["comment"] + (str(e),)
                result["result"] = False
            resource_id = ret["ret"]["TableDescription"]["TableName"]
            table_arn = ret["ret"].get("TableDescription").get("TableArn")
            existing_tags = hub.tool.aws.tag_utils.convert_tag_dict_to_list(tags)
            result["comment"] = result["comment"] + (
                f"Created aws.dynamodb.table '{resource_id}'",
            )
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = result["comment"] + (f"{e.__class__.__name__}: {e}",)
            result["result"] = False

    if ctx.get("test", False):
        result["new_state"] = plan_state
    elif not (before and before["result"]) or is_table_updated:
        after = await hub.exec.boto3.client.dynamodb.describe_table(
            ctx, TableName=resource_id
        )
        final_updated_tags = existing_tags
        if are_tags_updated:
            tags_ret = await hub.exec.boto3.client.dynamodb.list_tags_of_resource(
                ctx, ResourceArn=table_arn
            )
            if tags_ret.get("result") and tags_ret.get("ret"):
                final_updated_tags = tags_ret.get("ret").get("Tags")
        result[
            "new_state"
        ] = hub.tool.aws.dynamodb.conversion_utils.convert_raw_dynamodb_table_to_present(
            raw_resource=after["ret"].get("Table"),
            idem_resource_name=name,
            tags=final_updated_tags,
        )
    else:
        result["new_state"] = copy.deepcopy(result["old_state"])
    return result


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

    The DeleteTable operation deletes a table and all of its items. After a DeleteTable request, the specified table
    is in the DELETING state until DynamoDB completes the deletion. If the table is in the ACTIVE state, you can
    delete it. If a table is in CREATING or UPDATING states, then DynamoDB returns a ResourceInUseException. If the
    specified table does not exist, DynamoDB returns a ResourceNotFoundException. If table is already in the
    DELETING state, no error is returned.   DynamoDB might continue to accept data read and write operations, such
    as GetItem and PutItem, on a table in the DELETING state until the table deletion is complete.  When you delete
    a table, any indexes on that table are also deleted. If you have DynamoDB Streams enabled on the table, then the
    corresponding stream on that table goes into the DISABLED state, and the stream is automatically deleted after
    24 hours. Use the DescribeTable action to check the status of the table.

    Args:
        name(Text): The Idem name of the dynamoDB table.
        resource_id(Text, optional): AWS DynamoDB table name.
        timeout(Dict, optional): Timeout configuration for create/update/deletion of AWS DynamoDB Table.
            * delete (string) -- Timeout configuration for deletion of a DynamoDB Table
                * delay -- The amount of time in seconds to wait between attempts.
                * max_attempts -- Customized timeout configuration containing delay and max attempts.

    Request Syntax:
        [dynamodb_table-name]:
          aws.dynamodb.table.absent:
          - name: 'string'

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            test_dyanmoDB-table:
              aws.dynamodb.table.absent:
                - name: test_dynamoDB-table
                - resource_id: dyanmoDB_table-1e8965drf2c56902g:
    """

    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.dynamodb.table", name=name
        )
        return result
    before = await hub.exec.boto3.client.dynamodb.describe_table(
        ctx, TableName=resource_id
    )
    if not before:
        result["comment"] = hub.tool.aws.comment_utils.already_absent_comment(
            resource_type="aws.dynamodb.table", name=name
        )
    else:
        tags = await hub.exec.boto3.client.dynamodb.list_tags_of_resource(
            ctx, ResourceArn=before["ret"].get("Table").get("TableArn")
        )
        if tags.get("result"):
            existing_tags = tags.get("ret").get("Tags")
        else:
            result["comment"] = result["comment"] + tags["comment"]
            result["result"] = False
            return result

        result[
            "old_state"
        ] = hub.tool.aws.dynamodb.conversion_utils.convert_raw_dynamodb_table_to_present(
            raw_resource=before["ret"].get("Table"),
            idem_resource_name=name,
            tags=existing_tags,
        )
        if ctx.get("test", False):
            result["comment"] = hub.tool.aws.comment_utils.would_delete_comment(
                resource_type="aws.dynamodb.table", name=name
            )
            return result
        else:
            try:
                ret = await hub.exec.boto3.client.dynamodb.delete_table(
                    ctx, TableName=resource_id
                )
                result["result"] = ret["result"]
                if not result["result"]:
                    result["comment"] = ret["comment"]
                    return result
                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,
                )
                hub.log.debug(f"Waiting on deleting aws.dynamodb.table '{name}'")
                try:
                    await hub.tool.boto3.client.wait(
                        ctx,
                        "dynamodb",
                        "table_not_exists",
                        TableName=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="aws.dynamodb.table", name=name
                )
                after = await hub.exec.boto3.client.dynamodb.describe_table(
                    ctx, TableName=resource_id
                )
                if after["result"] and after["ret"]:
                    result[
                        "new_state"
                    ] = hub.tool.aws.dynamodb.conversion_utils.convert_raw_dynamodb_table_to_present(
                        raw_resource=after["ret"].get("Table"),
                        idem_resource_name=name,
                        tags=existing_tags,
                    )
            except hub.tool.boto3.exception.ClientError as e:
                result["comment"] = result["comment"] + (
                    f"{e.__class__.__name__}: {e}",
                )
                result["result"] = False
    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:
        Dict[str, Any]

    Examples:

        .. code-block:: bash

            $ idem describe aws.dynamodb.table
    """

    result = {}

    ret = await hub.exec.boto3.client.dynamodb.list_tables(ctx)
    if not ret["result"]:
        hub.log.debug(f"Could not describe table {ret['comment']}")
        return result
    if ret and ret["ret"] and ret["ret"].get("TableNames"):
        for table_name in ret["ret"].get("TableNames"):
            resource = await hub.exec.boto3.client.dynamodb.describe_table(
                ctx, TableName=table_name
            )
            if (
                resource.get("result")
                and resource.get("ret") is not None
                and resource.get("ret").get("Table")
            ):
                table_resource = resource.get("ret").get("Table")
            else:
                continue
            tags = await hub.exec.boto3.client.dynamodb.list_tags_of_resource(
                ctx, ResourceArn=table_resource.get("TableArn")
            )
            resource_converted = hub.tool.aws.dynamodb.conversion_utils.convert_raw_dynamodb_table_to_present(
                raw_resource=table_resource,
                idem_resource_name=table_name,
                tags=tags.get("ret").get("Tags") if tags.get("result") else None,
            )
            result[table_name] = {
                "aws.dynamodb.table.present": [
                    {parameter_key: parameter_value}
                    for parameter_key, parameter_value in resource_converted.items()
                ]
            }
    return result
