# V2.1.1d Beta
import traceback
from customtkinter import CTkFrame, CTk, CTkButton, CTkLabel, CTkEntry, CTkImage
from PIL import Image

from shared.utils import Logger

# =============== Validator Login View ===============
class ValidatorLoginView(CTkFrame):
    """Contains the elements of the user login interface."""
    def __init__(self, master,
            template: dict[str, str],
            images: 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 = "Validator Login View", log_file_name = "validator_app")

        # Master
        self.master: CTk = master
        
        # Template and images
        self.template: dict[str, str] = template
        self.images: dict[str, str] = images
        
        # Creates the view
        self.setup_view()
        
    # ========== Setup View ==========
    def setup_view(self):
        """Create the widgets, set template and window title."""
        try:
            # ===== Window Title =====
            self.master.title(self.template["WindowTitle"])
            # ========================
            
            # ===== Login Main Frame =====
            self.configure(**self.template["MainFrame"])
            self.pack(anchor = "center", padx = (0, 0), pady = (0, 0))
            self.pack_propagate(False)
            # ============================
            
            # ===== Image Label =====
            image = Image.open(self.images["login"])
            bgImage = CTkImage(
                light_image = image, dark_image = image,
                size = (
                    self.template["Image"]["width"],
                    self.template["Image"]["height"]))
            imageLabel = CTkLabel(master = self, text = "", image = bgImage)
            imageLabel.pack(anchor = "center", padx = (0, 0), pady = (0, 0))
            # =======================
            
            # ===== Auth Frame Widgets =====
            # Frame
            self.authFrame = CTkFrame(
                master = self,
                **self.template["AuthFrame"]["Frame"]
            )
            self.authFrame.place(anchor = "center", relx = 0.5, rely = 0.5)
            self.authFrame.propagate(False)
            # Title
            self.authTitleLabel = CTkLabel(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["TitleLabel"])
            )
            # Email Label
            self.authEmailLabel = CTkLabel(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["EmailLabel"])
            )
            # Email Entry
            self.authEmailEntry = CTkEntry(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["EmainPasswordEntry"])
            )
            # Password Label
            self.authPasswordLabel = CTkLabel(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["PasswordLabel"])
            )
            # Password Entry
            self.authPasswordEntry = CTkEntry(
                master = self.authFrame,
                show = "*",
                **self.template_processing(template = self.template["AuthFrame"]["EmainPasswordEntry"])
            )
            # Warning Label
            self.authWarningLabel = CTkLabel(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["WarningLabel"])
            )
            # Login Button
            self.authLoginButton = CTkButton(
                master = self.authFrame,
                **self.template_processing(template = self.template["AuthFrame"]["LoginButton"])
            )
            
            # Placement
            self.authTitleLabel.pack(anchor = "center", padx = (0, 0), pady = (35, 15))
            self.authEmailLabel.pack(anchor = "w", padx = (50, 0), pady = (0, 0))
            self.authEmailEntry.pack(anchor = "center", padx = (0, 0), pady = (0, 5))
            self.authPasswordLabel.pack(anchor = "w", padx = (50, 0), pady = (0, 0))
            self.authPasswordEntry.pack(anchor = "center", padx = (0, 0), pady = (0, 0))
            self.authWarningLabel.pack(anchor = "w", padx = (50, 0), pady = (0, 0))
            self.authLoginButton.pack(anchor = "center", padx = (0, 0), pady = (0, 0))
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.setup_view.__name__}] "
                f"Failed to create the login 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"])
                
            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}")
    # ======================================
# ====================================================