import shutil

import cv2
from config import constants
import os


class ImageSamplerService:

    def __init__(self, video_path):
        self.video_path = video_path


    def frame_diff(self, prev_frame, curr_frame):
        diff = cv2.absdiff(prev_frame, curr_frame)
        gray_diff = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
        return cv2.threshold(gray_diff, 50, 255, cv2.THRESH_BINARY)[1]


    def extract_slides(self, output_folder):
        cap = cv2.VideoCapture(self.video_path)
        fps = int(cap.get(cv2.CAP_PROP_FPS))
        frame_count = 0
        sample_count = 0
        sample_rate = 1 # we want 1 image per second --> for slides it should be enough
        success, prev_frame = cap.read()  # loads first image
        slide_counter = 0
        # remove potential previous images of slides
        shutil.rmtree(output_folder)
        os.makedirs(output_folder)
        while success:
            success, curr_frame = cap.read()
            if not success:
                break

            if frame_count % (fps * sample_rate) == 0:
                diff = self.frame_diff(prev_frame, curr_frame)
                if cv2.countNonZero(diff) > constants.MIN_FRAME_DIFF:
                    slide_counter += 1
                    slide_filename = os.path.join(output_folder, f"slide_{slide_counter}.png")
                    cv2.imwrite(slide_filename, curr_frame)

                prev_frame = curr_frame
                sample_count += 1
            frame_count += 1

        cap.release()
        return slide_counter

