import os
import cv2
import uuid
import json
import datetime 


from celery import Task
from celery.exceptions import MaxRetriesExceededError 

from app.tasks.worker import app 
from app.utils import find_static_folder_path, seconds_to_hhmmss, combine_json_files

@app.task(ignore_result=False, bind=True, base=Task)
def analyse(self, data, interval=1, save_xml=False): 

    try:
        
        static_path = find_static_folder_path()
        folder_name = f'{static_path}/{data["title"]}/{datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")}'
        
        #  Create Folder TMP For Images
        if not os.path.exists(f'{static_path}/tmp'):
            os.mkdir(f'{static_path}/tmp')

        #  Create Folder TMP For JSON Response
        if not os.path.exists(folder_name):
            os.makedirs(folder_name)

        # Start the timer
        start_time = datetime.datetime.now()

        # Read the video file into memory
        video = cv2.VideoCapture(data["source"])
            # Get the total number of frames in the video
        total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
        # Get 
        frame_rate = video.get(cv2.CAP_PROP_FPS)
        # Get video duration
        duration = seconds_to_hhmmss(total_frames/frame_rate)
        # Initialize the frame counter 
        counter = 0
        # 
        while video.isOpened():
            # Read the next frame from the video
            success, frame = video.read()
            # If we couldn't read a frame, exit the loop
            if not success:
                break
            # Extract every interval-th frame
            if counter % interval == 0:
                # Get Frame Time  
                frame_duration = seconds_to_hhmmss(counter/frame_rate)
                # 
                tmp_filename = f'{static_path}/tmp/{str(uuid.uuid4()).split("-")[0]}.png'
                cv2.imwrite(tmp_filename, frame)
                # start processing frame 
                command = f'python /var/www/html/BCA_API/app/tasks/detect_labels_deamon.py -i {tmp_filename} -f {counter} -d "{frame_duration}" -s {folder_name} > output.log &'
                os.system(command)
            # Increment the counter
            counter += 1

        # Get Final JSON File
        json_file_path = combine_json_files(
            folder_name,
            total_frames=total_frames, 
            interval=interval, 
            save_xml=save_xml
        )
        # Open the JSON file for reading
        with open(json_file_path, 'r') as json_file:
            # Load the JSON data
            data = json.load(json_file)
        message = f' ⛏️  : Processing Image/Video Complete - Input: {data["source"]} [{data["duration"]}] -  Time taken: {int((datetime.datetime.now() - start_time).total_seconds() * 1000)} ms '
        print(message)
        results = {
            "title": data["title"],
            "duration": data["duration"],
            "source": data["source"],
            'confidence': data["confidence"],
            'categories': data["categories"],
            'objects': data,
        }
        return {'status': 'SUCCESS', 'result': results}
    except Exception as ex:
        print(ex)
        try:
            self.retry(countdown=2)
        except MaxRetriesExceededError as ex:
            print(ex)
            return {'status': 'FAIL', 'result': 'max retried achieved'}