# V2.1.1d Beta
import traceback
from customtkinter import CTk

from shared.utils import Logger
from shared.contracts import RequestUpdateCallback
from .login_view import ValidatorLoginView
from validator.src.controllers.login_view_controller import LoginViewController
from .validator_view import ValidatorValidatorView
from validator.src.controllers.validator_view_controller import ValidatorViewController

# =============== Validator Window ===============
class ValidatorWindow(CTk):
    def __init__(self, 
        templates: dict[str, str], images: dict[str, str], kit_version: str,
        request_update_callback: RequestUpdateCallback,
        fg_color = None, **kwargs):
        super().__init__(fg_color, **kwargs)
        # Logger
        self.logger = Logger.create_logger(logger_name = "Validator Window", log_file_name = "validator_app")

        # Templates and images
        self.templates: dict[str, str] = templates
        self.images: dict[str, str] = images
        # Kit Version
        self.kitVersion = kit_version
        
        # Class Instances
        self.validatorLoginView: ValidatorLoginView | None = None
        self.validatorLoginViewController: LoginViewController | None = None
        
        self.validatorValidatorView: ValidatorValidatorView | None = None
        self.validatorValidatorViewController: ValidatorViewController | None = None
        
        # Callback Functions
        self.requestUpdateCallback: RequestUpdateCallback = request_update_callback
        
        # Setup Window
        self.setup_window()
        
    # ========== Window Functionality ==========
    def setup_window(self):
        """Set the window properties and icon."""
        try:
            # Template and Image
            windowTemplate: dict[str, str] = self.templates["validator_window"]
            logoImage: str = self.images["logo"]
            
            # Sets window attributes
            self.iconbitmap(logoImage)
            self.resizable(width = False, height = False)
            
            width = windowTemplate["window"]["width"]
            height = windowTemplate["window"]["height"]
            
            screenWidth = self.winfo_screenwidth()
            screenHeight = self.winfo_screenheight()
            
            midWidth = (screenWidth - int(width)) // 2
            midHeight = (screenHeight - int(height)) // 2
            
            # Place window
            self.geometry(f"{width}x{height}+{midWidth}+{midHeight}")
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.setup_window.__name__}] "
                f"Failed to setup the validator window. \n{traceBack}")
    # ==========================================
    
    # ========== Create Views ==========
    def create_login_view(self):
        """Create the login view and controller."""
        try:
            self.validatorLoginView = ValidatorLoginView(
                master = self,
                template = self.templates["login_view"],
                images = self.images
            )
            self.validatorLoginViewController = LoginViewController(
                view_master = self,
                login_view = self.validatorLoginView
            )
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.create_login_view.__name__}] "
                f"Failed to create the login view. \n{traceBack}")
    
    def create_validator_view(self):
        """Create the validator view and controller"""
        try:
            self.validatorValidatorView = ValidatorValidatorView(
                master = self,
                template = self.templates["validator_view"],
                images = self.images,
                kit_version = self.kitVersion
            )
            self.validatorValidatorViewController = ValidatorViewController(
                view_master = self,
                validator_view = self.validatorValidatorView,
                request_update_callback = self.requestUpdateCallback
            )
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.create_validator_view.__name__}] "
                f"Failed to create the validator view. \n{traceBack}")
    # ==================================
    
    # ========== Show Views ==========
    def show_login_view(self):
        """Show the login view."""
        try:
            if self.validatorValidatorView is not None:
                self.delete_validator_view()
            
            if self.validatorLoginView is None:
                self.create_login_view()
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.show_login_view.__name__}] "
                f"Failed to show the login view. \n{traceBack}")
        
    def show_validator_view(self):
        """Show the validator view"""
        try:
            if self.validatorLoginView is not None:
                self.delete_login_view()
                
            if self.validatorValidatorView is None:
                self.create_validator_view()
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.show_validator_view.__name__}] "
                f"Failed to show the validator view. \n{traceBack}")
    # ================================
    
    # ========== Delete Views ==========
    def delete_login_view(self):
        """Delete login view and controller instances."""
        try:
            self.validatorLoginViewController = None
            self.validatorLoginView = None
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.delete_login_view.__name__}] "
                f"Failed to delete the login view. \n{traceBack}")
    
    def delete_validator_view(self):
        """Delete controller view and controller instances."""
        try:
            self.validatorValidatorViewController = None
            self.validatorValidatorView = None
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.delete_validator_view.__name__}] "
                f"Failed to delete the validator view. \n{traceBack}")
    # ==================================
# ================================================