import traceback
from customtkinter import CTkFrame, CTk, CTkButton, CTkLabel, CTkImage, CTkEntry, CTkScrollableFrame, CTkProgressBar
from PIL import Image
import tkinter as tk

from shared.utils import Logger

# =============== Updater View ===============
class UpdaterView(CTkFrame):
    def __init__(self, master,
            template: dict[str, str],
            width = 200, height = 200, 
            corner_radius = None, border_width = None, 
            bg_color = "transparent", fg_color = None, 
            border_color = None, background_corner_colors = None, 
            overwrite_preferred_drawing_method = None, **kwargs):
        super().__init__(master, 
            width, height, 
            corner_radius, border_width, 
            bg_color, fg_color, 
            border_color, background_corner_colors, 
            overwrite_preferred_drawing_method, **kwargs)
        
        # Logger
        self.logger = Logger.create_logger(logger_name = "Updater View", log_file_name = "update_app")
        # Template
        self.template: dict[str, str] = template
        # Master
        self.master: CTk = master
        # Setup view
        self.setup_view()
        
    def setup_view(self) -> None:
        try:
            # ===== Window Title =====
            self.master.title(self.template["WindowTitle"])
            # self.master.protocol("WM_DELETE_WINDOW", lambda: None)
            # ========================
            
            # ===== Updater Main Frame =====
            self.configure(**self.template["MainFrame"])
            self.pack(anchor = "center", padx = (0, 0), pady = (0, 0))
            self.pack_propagate(False)
            # ============================
            
            # ===== Update Main Label =====
            self.updateLabelMain = CTkLabel(
                master = self,
                **self.template_processing(self.template["MainLabel"]))
            # ========================
            
            # ===== Update Progressbar =====
            self.updateProgressBar = CTkProgressBar(
                master = self,
                **self.template["Progressbar"])
            # ==============================
            
            # ===== Widget Placement =====
            self.updateLabelMain.pack(anchor = "w", padx = (75, 0), pady = (15, 0))
            self.updateProgressBar.pack(anchor = "center", padx = (0, 0), pady = (5, 0))
            # ============================
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.setup_view.__name__}] "
                f"Failed to setup the update view. \n{traceBack}")
    
    # ========== Template Helpers ==========
    def template_processing(self, template: dict[str, str]) -> dict[str, str]:
        """Process template to fix certain aspects."""
        try:
            templateFix = template.copy()
            if "font" in templateFix and isinstance(templateFix["font"], list):
                templateFix["font"] = tuple(templateFix["font"])
            if "dropdown_font" in templateFix and isinstance(templateFix["dropdown_font"], list):
                templateFix["dropdown_font"] = tuple(templateFix["dropdown_font"])
                
            return templateFix
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.template_processing.__name__}] "
                f"Failed to process template. \n{traceBack}")
    # ======================================
# ============================================