

import time
import boto3
from decouple import config
from celery import shared_task
from botocore.exceptions import ClientError

# Define the AWS region and service
AWS_REGION            = config("AWS_REGION", default="us-west-2", cast=str)
AWS_SERVICE           = "s3" # config("AWS_SERVICE", default="s3", cast=str)

# Set the AWS access key and secret access key
AWS_ACCESS_KEY_ID     = config("AWS_ACCESS_KEY_ID", default="", cast=str)
AWS_SECRET_ACCESS_KEY = config("AWS_SECRET_ACCESS_KEY", default="", cast=str)

# Define a Celery task that checks for the existence of an SRT file in an S3 bucket
@shared_task(name="check SRT")
def check_for_SRT_file(key):

    # Set the name of the S3 bucket to check
    bucket_name = "convertion-html-to-srt"
    # Create an S3 client object using the Boto3 library
    s3 = boto3.client(
        AWS_SERVICE,
        aws_access_key_id=AWS_ACCESS_KEY_ID,
        aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
        region_name=AWS_REGION
    )
    # Loop until the SRT file is found in the bucket
    while True:
        try:
            # Try to get the metadata for the SRT file using the S3 head_object method
            s3.head_object(Bucket=bucket_name, Key=key)
            # If the head_object method succeeds, the SRT file exists in the bucket, so return a success message & download it to a local file
            with open("/var/www/html/subscibe_interface/"+key, 'wb') as f:
                s3.download_fileobj(bucket_name, key, f)
            # Save the downloaded SRT file to the database using Django ORM
            # srt_file = SRTFile.objects.create(name=key)
            # srt_file.srt_file.save(key, open(key, 'rb'))
            srt_file = ""
            print(f"File {key} found in S3 bucket {bucket_name}!")
            return {"message" :f"File {key} found in S3 bucket {bucket_name}!", "file":srt_file}
        except ClientError as e:
            # If the head_object method fails with a 404 (Not Found) error, the SRT file does not yet exist in the bucket,
            # so sleep for 5 seconds before trying again
            if e.response['Error']['Code'] == '404':
                print("File Not Found")
                time.sleep(5)
            # If the head_object method fails with any other error, re-raise the exception so that it can be logged or handled
            # elsewhere in the application
            else:
                raise

def on_s3_file_found(result):
    print(result)