from glob import glob
import os
from datos.Config import ConfigManager
import logica.controladores.segmentation_controller as controlador

config = ConfigManager()

def segmentar_video_callback():

    FPS = controlador.get_fps()
    
    ffmpeg_binary = "ffmpeg"

    current_path = os.path.dirname(os.path.realpath(__file__))
    father_path = os.path.dirname(current_path)
    script_path = os.path.join(father_path, "Scripts")

	# On Windows, if FFmpeg isn't found, try automatically downloading it from the internet
    if os.name == "nt" and os.system(f"where {ffmpeg_binary} >nul 2>nul") != 0:
        ffmpeg_glob = os.path.join(script_path, "external", "ffmpeg", "*", "bin", "ffmpeg.exe")
        candidates = glob(ffmpeg_glob)

        if not candidates:
            down_result = controlador.init_process(os.path.join(script_path, "download_ffmpeg.bat"))
            if down_result != 0:
                controlador.set_output("Error downloading ffmpeg.")

            else:
                controlador.set_output("Ffmpeg loaded correctly.")
                
            candidates = glob(ffmpeg_glob)

        if candidates:
            ffmpeg_binary = candidates[0]
            
    result = f"{ffmpeg_binary} -i {config.DIR_VIDEO} -qscale:v 1 -qmin 1 -vf \"fps={float(FPS)},format=rgb24\" {config.IMAGES_FOLDER}\%04d.{config.FILE_TYPE}"
    controlador.init_process(result)

    controlador.set_output(controlador.cargar_imagenes(config.IMAGES_FOLDER))