import subprocess
import cv2
import numpy as np
import time
import datetime

def compare_image(image_1, image_2):
    start_time = time.time()
    first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
    second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])
    img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
    img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
    img_template_diff = 1 - img_template_probability_match
    commutative_image_diff = (img_hist_diff * 0.75) + img_template_diff
    end_time = time.time()
    return commutative_image_diff


# Replace the URLs with the actual file paths
show1_1 = cv2.imread("shows_iframes/wa3d/wa3d1.png")
show1_2 = cv2.imread("shows_iframes/wa3d/wa3d2.png")
show1_3 = cv2.imread("shows_iframes/wa3d/wa3d3.png")
show1_4 = cv2.imread("shows_iframes/wa3d/wa3d4.png")
show2_1 = cv2.imread("shows_iframes/INFO_SOIR/info1.png")
show2_2 = cv2.imread("shows_iframes/INFO_SOIR/info2.png")
show2_3 = cv2.imread("shows_iframes/INFO_SOIR/info3.png")
# show2_4 = cv2.imread("shows_iframes/INFO_SOIR/info4.png")
# show3_1 = cv2.imread("shows_iframes/AL_MASSAIYA/AL_MASSAIYA1.png")
show3_2 = cv2.imread("shows_iframes/AL_MASSAIYA/AL_MASSAIYA2.png")
show3_3 = cv2.imread("shows_iframes/AL_MASSAIYA/AL_MASSAIYA3.png")
show3_4 = cv2.imread("shows_iframes/AL_MASSAIYA/AL_MASSAIYA4.png")
reference_iframes = {
    "show1": [show1_1, show1_2, show1_3,show1_4],
    "show2": [show2_1, show2_2, show2_3],
    "show3": [show3_2, show3_3,show3_4],
}

# select=gt(scene\,0.10)
# Construct the FFmpeg command
live_stream_url = "test.ts" #"http://your-live-stream-url/playlist.m3u8"
command = [
    "ffmpeg",
    "-re",
    "-i", live_stream_url,
    "-vf", "select='gt(scene\,0.10)'",
    "-vsync", "vfr",
    "-q:v", "2",
    "-f", "image2pipe",
    "-vcodec", "mjpeg",
    "-"
]



# Run the command and create a pipe to read the output
ffmpeg_process = subprocess.Popen(command, stdout=subprocess.PIPE)

# Read the MJPEG stream from the pipe
data = bytearray()
while True:
    buf = ffmpeg_process.stdout.read(1024)
    if not buf:
        break
    data += buf

    # Find the start and end markers of a JPEG frame (0xFF, 0xD8, and 0xFF, 0xD9)
    start_marker = data.find(b'\xff\xd8')
    end_marker = data.find(b'\xff\xd9')

    # Extract the JPEG frame and remove it from the data buffer
    if start_marker != -1 and end_marker != -1:
        jpeg_data = data[start_marker:end_marker+2]
        data = data[end_marker+2:]

        # Convert the JPEG data to an OpenCV image
        iframe_image = cv2.imdecode(np.frombuffer(jpeg_data, dtype=np.uint8), cv2.IMREAD_COLOR)
        # cv2.imwrite(f"iframes_saved/.png", ref_iframe)

        timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        filename = f"iframes_saved/index_{timestamp}.png"
        cv2.imwrite(filename, iframe_image)
