import cv2
import uuid
import datetime

from utils import *

@execute_time
def analyse(input_path, input_type=None, interval=None):
    # 
    total_frames = 0 
    # 
    file_name, _ = os.path.splitext(os.path.basename(input_path))
    # 
    folder_name = f'{file_name}/{datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")}'
    #  Create Folder TMP For Images
    if not os.path.exists("tmp"):
        os.mkdir("tmp")
    #  Create Folder TMP For JSON Response
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)

    if input_type == 'image':
        # 
        image = cv2.imread(input_path)
        # 
        tmp_filename = f'tmp/{str(uuid.uuid4()).split("-")[0]}.png'
        cv2.imwrite(tmp_filename, image)
        # start processing frame
        full_path = os.path.join(os.getcwd(), tmp_filename)
        command = f'python detect_labels_deamon.py -i {full_path} -s {folder_name} > output.log &'
        os.system(command)

    if input_type == 'video':
        # Read the video file into memory
        video = cv2.VideoCapture(input_path)
         # 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'tmp/{str(uuid.uuid4()).split("-")[0]}.png'
                cv2.imwrite(tmp_filename, frame)
                # start processing frame
                full_path = os.path.join(os.getcwd(), tmp_filename)
                command = f'python detect_labels_deamon.py -i {full_path} -f {counter} -d "{frame_duration}" -s {folder_name} > output.log &'
                os.system(command)
            # Increment the counter
            counter += 1
    
    return total_frames, folder_name

if __name__ == '__main__':  

    import os
    import argparse
    import mimetypes

    # Create an argument parser
    parser = argparse.ArgumentParser(description="Analyze Video By Extracting Video Content", prog="VideoAnalyzer", epilog="Thanks for using %(prog)s ! 🚀", )
    # Add the argument for the video path
    parser.add_argument("-i", "--input", type=str, help="The path to the video file", required=True)
    # Add the argument for the interval
    parser.add_argument("-frame", "--interval", type=int, default=1, help="The interval at which to extract the MetaData")
    # Add the argument for saving the result as a JSON file
    parser.add_argument("-xml", "--save-xml", action="store_true", default=False, help="Save the result as a XML file")
    # Add the argument for project version
    parser.add_argument("-v", "--version", action="version", version="%(prog)s V 0.1.0 🚀")
    # Parse the command line arguments
    args = parser.parse_args()

    # 
    try:
        # 
        if not args.input:
            raise ValueError("[Error][Message : Input Path is Required, Please Provide Input Path.]")
        # 
        if not os.path.exists(args.input):
            print(f"[Error][< {args.input} >][Message : The Target Directory Doesn't Exist.]")
            raise SystemExit(1)
        # 
        if not os.path.isfile(args.input):
            print(f"[Error][< {args.input} >][Message : The Input Path Is Not A File.]")
            raise SystemExit(1)
        # 
        print(" 🚀 : Start Processing The Image/Video, Please Wait ...")

        # Start the timer
        start_time = datetime.datetime.now()
        # 
        input_type = mimetypes.guess_type(args.input)[0]
        # 
        if input_type.startswith("image"):
            input_type = "image"
        elif input_type.startswith("video"):
            input_type =  "video"
        # Lanch The Processing
        total_frames, folder = analyse(args.input, input_type, args.interval)
        # Get Final JSON File
        combine_json_files(
            folder,
            total_frames=total_frames, 
            interval=args.interval, 
            save_xml=args.save_xml
        )
        # 
        print(f" ⛏️  : Processing Image/Video Complete - File: {args.input} -  Time taken: {int((datetime.datetime.now() - start_time).total_seconds() * 1000)} ms  ")
        # 
        print(" 💻 : Processing Image/Video Finished, Thanks For patience ")        
        
    # 
    except ValueError as ve:
        print(ve)
        parser.print_help()
    # 
    except Exception as e:
        print(f"An error occurred: {e}")


