
import logging
import tkinter as tk
from tkinter import E, W, filedialog, ttk

from PIL import Image, ImageTk

from utils.solver_checker import check_solver

from spr.runthread import RunSprThread

main_logger = logging.getLogger('spr')

class FormUi:

    runspr_thread = None

    def __init__(self, frame, q):
        self.frame = frame
        self.q = q
        image = Image.open('gui/img/icons/icons8-play-16.png')
        self.photo = ImageTk.PhotoImage(image)

        opfile = Image.open('gui/img/icons/icons8-abrir-carpeta-16.png')
        self.opfile = ImageTk.PhotoImage(opfile)

        # Add a text field for file path
        self.file_path = tk.StringVar()
        ttk.Label(self.frame, text='Archivo:').grid(
            column=0, row=0, sticky=W, pady=(5, 5), padx=(0, 10))
        self.entry = ttk.Entry(self.frame, textvariable=self.file_path,
                               width=50)
        self.entry.grid(column=1, row=0, sticky=(W, E), pady=(5, 5))

        
        
        self.button = ttk.Button(
            self.frame, image=self.opfile, compound='center',
            command=self.open_file_dialog, width=3)
        self.button.grid(column=2, row=0, sticky=W)



        self.all_day = tk.IntVar()
        self.all_day_cb = ttk.Checkbutton(self.frame, text="Ejecutar 24 períodos", variable=self.all_day, command=self.chkbox_state)
        self.all_day_cb.state(['selected'])
        self.all_day.set(1)
        self.all_day_cb.grid(column=1, row=1, sticky=W)




        periodos = [*range(0,24)]
        ttk.Label(self.frame, text='Periodo:').grid(
            column=0, row=2, sticky=W, pady=(5, 5), padx=(0, 10))
        self.period_combo = ttk.Combobox(self.frame, values=periodos)
        self.period_combo.current(0)
        self.period_combo.set(23)
        self.period_combo.configure(state='disabled')
        self.period_combo.grid(column=1, row=2, sticky=W)



        self.button_run = ttk.Button(self.frame, image=self.photo,
                                     compound="right", text='Ejecutar',
                                     command=self.run)
        self.button_run.grid(column=1, row=3, sticky=W)

        

    def open_file_dialog(self):
        # Open file dialog
        try:
            file = filedialog.askopenfilename(
                filetypes=[('Excel', '.xlsx')],
                title='Seleccione un archivo de predespacho...')
        except Exception as e:
            main_logger.error(e)
            self.file_path.set('')
        else:
            main_logger.info(f'Archivo seleccionado: {file}')
            self.file_path.set(file)

    def chkbox_state(self):
        if self.all_day_cb.instate(['selected']):
            self.period_combo.configure(state='disabled')
            self.period_combo.current(0)
            self.period_combo.set(23)
        else:
            self.period_combo.configure(state='normal')

    def run(self):
           
        try:
            check_solver()

            if not self.file_path.get():
                return

            inputfile = self.file_path.get()
            all_day = self.all_day.get()
            if all_day == 1:
                all_day = True
            else:
                all_day = False

            period = self.period_combo.get()

            
            self.button_run.configure(state='disabled')

            self.runspr_thread = RunSprThread(args=(inputfile,int(period),all_day))
            self.runspr_thread.start()

            self.check_thread()

        except Exception as e:
            main_logger.error(e)

            return

    def check_thread(self):

        if not self.runspr_thread.is_alive():
            self.button_run.configure(state='normal')
            self.q.put(False)
        else:
            self.q.put(True)
            self.frame.after(100, self.check_thread)
