import os
import dearpygui.dearpygui as dpg
from datos.Config import ConfigManager
import logica.controladores.segmentation_controller as controlador
from log_register.Register import Register

registro = Register()
config = ConfigManager()

is_updating = True

def seleccionar_video_callback():
    result = controlador.seleccionar_video()
    if result != -1:
        base_folder = os.path.dirname(result)
        config.set_base_folder(base_folder)
        
        config.set_video_folder(result)
        dpg.configure_item("video_seleccionado", default_value=config.DIR_VIDEO)
        registro.append_config("DIR_VIDEO", config.DIR_VIDEO)

def seleccionar_folder_callback():
    result, folder = controlador.seleccionar_folder()

    if result == 0:
        config.set_images_folder(folder)
        dpg.configure_item("text_carpeta_segmentacion", default_value=config.IMAGES_FOLDER)
        controlador.set_output(controlador.cargar_imagenes(config.IMAGES_FOLDER))

        registro.append_config("IMAGES_FOLDER", config.IMAGES_FOLDER)

def callback_delete_images(sender):
    if not config.is_images_folder_set() and not os.path.exists(config.IMAGES_FOLDER):
        controlador.set_output("Output folder not selected or does not exist.")
        return
    
    result = controlador.delete_images(config.IMAGES_FOLDER)
    controlador.set_output(result)
    controlador.set_output(controlador.cargar_imagenes(config.IMAGES_FOLDER))
    
def set_model_camera(sender):
    # Uncheck all other checkboxes
    for checkbox_tag in ["SIMPLE_PINHOLE", "SIMPLE_RADIAL", "SIMPLE_RADIAL_FISHEYE", "OPENCV"]:
        if checkbox_tag != sender:
            dpg.set_value(checkbox_tag, False)

    config.set_camera_model(sender)

    registro.append_config("MODEL_CAMERA", config.MODEL_CAMERA)

def configure_model_camera():
    for checkbox_tag in ["SIMPLE_PINHOLE", "SIMPLE_RADIAL", "SIMPLE_RADIAL_FISHEYE", "OPENCV"]:
        dpg.set_value(checkbox_tag, is_config(checkbox_tag))

def callback_configure_output_file(sender):
    for checkbox_tag in ["png", "jpg", "tiff", "bmp"]:
        # all false except the selected one
        if checkbox_tag != sender:
            dpg.set_value(checkbox_tag, False)
        else:
            dpg.set_value(checkbox_tag, True)
            
    config.set_output_file_type(sender)
    registro.append_config("FILE_TYPE", sender)

def update_data(sender):
    global is_updating

    if is_updating == False:
        dpg.configure_item("video_seleccionado", default_value=config.DIR_VIDEO)
        dpg.configure_item("text_carpeta_segmentacion", default_value=config.IMAGES_FOLDER)
        dpg.configure_item("fps", default_value=config.FPS)
        dpg.configure_item("png", default_value=type_config_callback("png"))
        dpg.configure_item("jpg", default_value=type_config_callback("jpg"))
        dpg.configure_item("tiff", default_value=type_config_callback("tiff"))
        dpg.configure_item("bmp", default_value=type_config_callback("bmp"))

    configure_model_camera()

    if config.is_images_folder_set():
        tag = controlador.get_group_tag()
        result = dpg.get_item_configuration(tag)["show"]

        if not result:
            dpg.configure_item(tag, show=True)
            controlador.set_output(controlador.cargar_imagenes(config.IMAGES_FOLDER))

def type_config_callback(type):
    return config.FILE_TYPE == type

def main_view(parent):
    # Initialize log view and texture controller
    controlador.init_output_view()

    grupo_general = dpg.add_group(parent=parent, tag="segmentation", show=True)

    dpg.add_spacer(height=20, parent=grupo_general)

    with dpg.group(horizontal=True, show=True, parent=grupo_general):
        dpg.add_button(label="Select Video", callback=seleccionar_video_callback, show=True)
        dpg.add_button(label="Select Output", callback=seleccionar_folder_callback, show=True)

    dpg.add_spacer(height=5, parent=grupo_general)

    with dpg.group(horizontal=False, show=True, tag="carpeta_segmentacion", parent=grupo_general):
        dpg.add_input_text(label="Selected Video", show=True, default_value=config.DIR_VIDEO, enabled=False, tag="video_seleccionado")

        dpg.add_spacer(height=5, parent="carpeta_segmentacion")

        dpg.add_input_text(label="Segmentation Output Folder", show=True, default_value=config.IMAGES_FOLDER, enabled=False, tag="text_carpeta_segmentacion")

        dpg.add_spacer(height=15, parent=grupo_general)
        
        with dpg.group(horizontal=True, show=True, tag="segmentar", parent=grupo_general):
            dpg.add_slider_int(label="FPS", min_value=1, max_value=10, default_value=config.FPS, tag="fps", callback=update_fps_callback, show=True)

        dpg.add_spacer(height=5, parent=grupo_general)

        with dpg.group(horizontal=True, show=True, tag="type_output_file", parent=grupo_general):
            dpg.add_text("Output File Type:", show=True)

            with dpg.group(horizontal=True, show=True, tag="output_file", parent=grupo_general):
                dpg.add_checkbox(label="PNG", default_value=type_config_callback("png"), show=True, tag="png", callback=callback_configure_output_file)
                dpg.add_checkbox(label="JPG", default_value=type_config_callback("jpg"), show=True, tag="jpg", callback=callback_configure_output_file)
                dpg.add_checkbox(label="TIFF", default_value=type_config_callback("tiff"), show=True, tag="tiff", callback=callback_configure_output_file)
                dpg.add_checkbox(label="BMP", default_value=type_config_callback("bmp"), show=True, tag="bmp", callback=callback_configure_output_file)

        dpg.add_spacer(height=5, parent=grupo_general)

        with dpg.group(horizontal=False, show=True, tag="main_options", parent=grupo_general):
            dpg.add_text("Camera Model:", show=True)

            with dpg.group(horizontal=True, show=True, tag="options", parent=grupo_general):
                dpg.add_checkbox(label="Simple Pinhole", default_value=is_config("SIMPLE_PINHOLE"), show=True, callback=set_model_camera, tag="SIMPLE_PINHOLE")
                dpg.add_checkbox(label="Simple Radial", default_value=is_config("SIMPLE_RADIAL"), show=True, callback=set_model_camera, tag="SIMPLE_RADIAL")
                dpg.add_checkbox(label="Radial Fisheye", default_value=is_config("SIMPLE_RADIAL_FISHEYE"), show=True, callback=set_model_camera, tag="SIMPLE_RADIAL_FISHEYE")
                dpg.add_checkbox(label="OpenCV", default_value=is_config("OPENCV"), show=True, callback=set_model_camera, tag="OPENCV")

    dpg.add_spacer(height=25, show=True, parent=grupo_general)

    with dpg.group(horizontal=True, tag="buttons_segmentar", parent=grupo_general):
        dpg.add_button(label="Segment", callback=segmentar_video_callback, show=True, width=100, height=30)
        dpg.add_button(label="Delete Images", callback=callback_delete_images, show=True, width=150, height=30)

    dpg.add_spacer(height=20, parent=grupo_general)

    with dpg.group(horizontal=False, show=True, tag="imagenes", parent=grupo_general):
        dpg.add_text("Segmentation Images:", show=True)
        dpg.add_spacer(height=15, parent="imagenes")

        with dpg.group(horizontal=True, show=True, tag="imagenes_group"):
            dpg.add_spacer(width=70, parent="imagenes_group")

    with dpg.item_handler_registry(show=False, tag="handler") as handler_segmentation:
        dpg.add_item_visible_handler(callback=update_data)

    dpg.bind_item_handler_registry("segmentation", "handler")

    init_texture_view()

def is_config(model):
    return config.MODEL_CAMERA == model

def update_fps_callback():
    config.set_fps(dpg.get_value("fps"))
    registro.append_config("FPS", dpg.get_value("fps"))


def is_file_type():
    for checkbox_tag in ["png", "jpg", "tiff", "bmp"]:
        if dpg.get_value(checkbox_tag):
            return True
        
    return False

def segmentar_video_callback():
    if not is_file_type():
        controlador.set_output("No file type selected.")
        return

    FPS = dpg.get_value("fps")
    controlador.set_fps(FPS)

    controlador.segmentar_video()

def show_view():
    global is_updating
    is_updating = False
    
    update_data(None)
    is_updating = True

    dpg.show_item("segmentation")
    
def init_texture_view():
    controlador.init_texture_view(config.IMAGES_FOLDER)