import dearpygui.dearpygui as dpg
from datos.Config import ConfigManager
import os
import logica.utilidades.utils as ut
import uuid

config = ConfigManager()

class TextureController:
    imagenes = []

    def __init__(self, parent):
        self.parent = parent
        self.LAST_TEXTURE = str(uuid.uuid4())
        self.tag = str(uuid.uuid4())
        self.group_tag = str(uuid.uuid4())
        self.slider_id = 0

    def load_texture(self, data_file):

        if data_file != None:
            width, height, channels, data = dpg.load_image(data_file)

        else:
            width, height, channels, data = dpg.load_image(config.DEFAULT_IMAGE)

        config.set_image_global_size(width, height) 

        if dpg.does_item_exist(self.LAST_TEXTURE):
            dpg.delete_item(self.LAST_TEXTURE)

        self.LAST_TEXTURE = str(uuid.uuid4())

        with dpg.texture_registry(show=False):
            dpg.add_dynamic_texture(config.IMAGE_GLOBAL_WIDTH, config.IMAGE_GLOBAL_HEIGHT, data, tag=self.LAST_TEXTURE)
        
        if dpg.does_item_exist(self.tag):
            dpg.delete_item(self.tag)

        dpg.add_image(self.LAST_TEXTURE, width=config.DEFAULT_WIDTH, height=config.DEFAULT_HEIGHT, parent=self.group_tag, tag=self.tag)

    # Función de callback para actualizar la imagen según el valor del slider
    def _slider_callback(self, sender):
        valor_slider = dpg.get_value(sender)
        imagen_actual = int(valor_slider)
        
        # Actualizar la imagen en la ventana
        self.load_texture(self.imagenes[imagen_actual])

    def main_view(self, folder):
        # Añadimos un slider para recorrer las imágenes
        with dpg.group(horizontal=False, show=False, tag=self.group_tag, parent=self.parent):
            dpg.add_text("Frames:")
            self.slider_id = dpg.add_slider_int(min_value=0, max_value=0, callback=self._slider_callback)

            dpg.add_spacer(height=10)

        if not os.path.isdir(folder):
            return "The specified folder does not exist."
         
        return self.cargar_imagenes(folder)

    # Función para cargar las imágenes desde una carpeta
    def cargar_imagenes(self, folder):

        dpg.show_item(self.group_tag)

        result, self.imagenes = ut.cargarImagesArchivos(folder)
        if len(self.imagenes) == 0:
            self.load_texture(None)
            dpg.set_value(self.slider_id, 0)
            dpg.configure_item(self.slider_id, max_value=0)
            return result

        # Actualizar el slider y la imagen en la ventana
        dpg.set_value(self.slider_id, 0)
        dpg.configure_item(self.slider_id, max_value=len(self.imagenes) - 1)
        
        self.load_texture(self.imagenes[0])

        return result
    
    def get_group_tag(self):
        return self.group_tag
