import queue
import tkinter as tk
from tkinter import E, N, S, W, ttk
from tkinter.scrolledtext import ScrolledText

from PIL import Image, ImageTk


class ConsoleUi:
    """Poll messages from a logging queue and display them in a scrolled text
    widget"""

    def __init__(self, frame, q, qh):
        self.frame = frame
        self.log_queue = q
        self.queue_handler = qh

        trash_icon = Image.open('gui/img/icons/icons8-eliminar-16.png')
        self.trash_icon = ImageTk.PhotoImage(trash_icon)
        # Create a ScrolledText wdiget
        self.scrolled_text = ScrolledText(frame, state='disabled', height=25)
        self.scrolled_text.grid(row=0, column=0, sticky=(N, S, W, E))
        self.clear = ttk.Button(frame, text='Limpiar Log',
                                command=self.clear_console,
                                image=self.trash_icon,
                                compoun='right')
        self.clear.grid(row=1, column=0, sticky=E, pady=(5, 5))
        # Font config
        self.scrolled_text.configure(font='TkFixedFont')
        self.scrolled_text.tag_config('INFO', foreground='black')
        self.scrolled_text.tag_config('DEBUG', foreground='gray')
        self.scrolled_text.tag_config('WARNING', foreground='orange')
        self.scrolled_text.tag_config('ERROR', foreground='red')
        self.scrolled_text.tag_config(
            'CRITICAL', foreground='red', underline=1)
        # Create a logging handler using a queue

        # self.queue_handler = QueueHandler(self.log_queue)
        # formatter = logging.Formatter(
        #     '%(asctime)s: %(message)s', datefmt='%Y-%m-%dT%H:%M:%S')
        # self.queue_handler.setFormatter(formatter)
        # # self.queue_handler.setLevel(logging.INFO)
        # logger.addHandler(self.queue_handler)
        # Start polling messages from the queue
        self.frame.after(100, self.poll_log_queue)

    def display(self, record):
        msg = self.queue_handler.format(record)
        self.scrolled_text.configure(state='normal')
        self.scrolled_text.insert(tk.END, msg + '\n', record.levelname)
        self.scrolled_text.configure(state='disabled')
        # Autoscroll to the bottom
        self.scrolled_text.yview(tk.END)

    def poll_log_queue(self):
        # Check every 100ms if there is a new message in the queue to display
        while True:
            try:
                record = self.log_queue.get(block=False)
            except queue.Empty:
                break
            else:
                self.display(record)
        self.frame.after(100, self.poll_log_queue)

    def clear_console(self):
        self.scrolled_text.configure(state='normal')
        self.scrolled_text.delete(1.0, tk.END)
        self.scrolled_text.configure(state='disabled')
