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

hub.exec.boto3.client.s3.delete_bucket_policy
hub.exec.boto3.client.s3.get_bucket_policy
hub.exec.boto3.client.s3.put_bucket_policy
resource = hub.tool.boto3.resource.create(ctx, "s3", "BucketPolicy", name)
hub.tool.boto3.resource.exec(resource, delete, *args, **kwargs)
hub.tool.boto3.resource.exec(resource, put, *args, **kwargs)
"""



from typing import *
import dict_tools.differ as differ
async def present(hub, ctx, name: Text, bucket: Text, policy: Text, content_md5: Text = None, confirm_remove_self_bucket_access: bool = None, expected_bucket_owner: Text = None)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    Applies an Amazon S3 bucket policy to an Amazon S3 bucket. If you are using an identity other than the root user
    of the Amazon Web Services account that owns the bucket, the calling identity must have the PutBucketPolicy
    permissions on the specified bucket and belong to the bucket owner's account in order to use this operation. If
    you don't have PutBucketPolicy permissions, Amazon S3 returns a 403 Access Denied error. If you have the correct
    permissions, but you're not using an identity that belongs to the bucket owner's account, Amazon S3 returns a
    405 Method Not Allowed error.   As a security precaution, the root user of the Amazon Web Services account that
    owns a bucket can always use this operation, even if the policy explicitly denies the root user the ability to
    perform this action.   For more information, see Bucket policy examples. The following operations are related to
    PutBucketPolicy:    CreateBucket     DeleteBucket

    Args:
        name(Text): A name, ID, or JMES search path to identify the resource.
        bucket(Text): The name of the bucket.
        content_md5(Text, optional): The MD5 hash of the request body. For requests made using the Amazon Web Services Command Line
            Interface (CLI) or Amazon Web Services SDKs, this field is calculated automatically. Defaults to None.
        confirm_remove_self_bucket_access(bool, optional): Set this parameter to true to confirm that you want to remove your permissions to change this
            bucket policy in the future. Defaults to None.
        policy(Text): The bucket policy as a JSON document.
        expected_bucket_owner(Text, optional): The account ID of the expected bucket owner. If the bucket is owned by a different account, the
            request will fail with an HTTP 403 (Access Denied) error. Defaults to None.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_present:
              aws_auto.s3.bucket_policy.present:
                - name: value
                - bucket: value
                - policy: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.s3.bucket_policy.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    resource = hub.tool.boto3.resource.create(ctx, "s3", "BucketPolicy", name)
    before = await hub.tool.boto3.resource.describe(resource)

    if before:
        result["comment"] = f"'{name}' already exists"
    else:
        try:
            ret = await hub.exec.boto3.client.s3.put_bucket_policy(
                ctx,
                
                
                **{"Bucket": bucket, "ContentMD5": content_md5, "ConfirmRemoveSelfBucketAccess": confirm_remove_self_bucket_access, "Policy": policy, "ExpectedBucketOwner": expected_bucket_owner}
            )
            result["result"] = ret["status"]
            if not result["result"]:
                result["comment"] = ret["comment"]
                return result
            ret["comment"] = f"Created '{name}'"
        except hub.tool.boto3.exception.ClientError as e:
            result["comment"] = f"{e.__class__.__name__}: {e}"

    
    # TODO perform other modifications as needed here
    ...

    after = await hub.tool.boto3.resource.describe(resource)
    result["changes"] = differ.deep_diff(before, after)
    return result

async def absent(hub, ctx, name: Text, bucket: Text, expected_bucket_owner: Text = None)  -> Dict[str, Any]:
    r'''
    **Autogenerated function**
    
    This implementation of the DELETE action uses the policy subresource to delete the policy of a specified bucket.
    If you are using an identity other than the root user of the Amazon Web Services account that owns the bucket,
    the calling identity must have the DeleteBucketPolicy permissions on the specified bucket and belong to the
    bucket owner's account to use this operation.  If you don't have DeleteBucketPolicy permissions, Amazon S3
    returns a 403 Access Denied error. If you have the correct permissions, but you're not using an identity that
    belongs to the bucket owner's account, Amazon S3 returns a 405 Method Not Allowed error.   As a security
    precaution, the root user of the Amazon Web Services account that owns a bucket can always use this operation,
    even if the policy explicitly denies the root user the ability to perform this action.  For more information
    about bucket policies, see Using Bucket Policies and UserPolicies.  The following operations are related to
    DeleteBucketPolicy     CreateBucket     DeleteObject

    Args:
        name(Text): A name, ID, or JMES search path to identify the resource.
        bucket(Text): The bucket name.
        expected_bucket_owner(Text, optional): The account ID of the expected bucket owner. If the bucket is owned by a different account, the
            request will fail with an HTTP 403 (Access Denied) error. Defaults to None.

    Returns:
        Dict[str, Any]

    Examples:

        .. code-block:: sls

            resource_is_absent:
              aws_auto.s3.bucket_policy.absent:
                - name: value
                - bucket: value
    '''
    
    result = dict(comment="", changes= None, name=name, result=True)
    ret = await hub.exec.boto3.client.s3.bucket_policy.id(
        ctx,
        jmes_path=name
    )
    if ret["status"]:
        # name is now the first id that matched the JMES search path
        name = ret["ret"]
    

    resource = hub.tool.boto3.resource.create(ctx, "s3", "BucketPolicy", name)

    before = await hub.tool.boto3.resource.describe(resource)

    if not before:
        result["comment"] = f"'{name}' already absent"
    else:
        try:
            ret = await hub.exec.boto3.client.s3.delete_bucket_policy(
                ctx,
                
                
                **{"Bucket": bucket, "ExpectedBucketOwner": expected_bucket_owner}
            )
            result["result"] = ret["status"]
            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}"

    

    after = await hub.tool.boto3.resource.describe(resource)
    result["changes"] = differ.deep_diff(before, after)
    return result

