import traceback

from shared.utils import Logger, AssetLoader, ConfigManager
from shared.contracts import RequestUpdateCallback
from validator.src.ui.validator_window import ValidatorWindow
from validator.src.controllers.validator_window_controller import ValidatorWindowController
# =============== Validation App ===============
class ValidatorApp():
    def __init__(self, request_update: RequestUpdateCallback):
        # Logger
        self.logger = Logger.create_logger(logger_name = "Validation App", log_file_name = "validator_app")

        # Helper Classes Instances
        self.configManager: ConfigManager = ConfigManager()
        self.assetLoader: AssetLoader | None = None
        self.validatorWindowInstance: ValidatorWindow | None = None
        
        # Callback Function
        self.requestUpdateCallback: RequestUpdateCallback = request_update
    # ========== Functionality ==========
    def start_window(self):
        """Start the validator window."""
        try:
            if self.validatorWindowInstance is None:
                self.assetsLoaderInstance = AssetLoader(template_type = "Validator")
                kitVersion = self.configManager.get_value(section = "VERSION", key = "kit")
                
                self.validatorWindowInstance = ValidatorWindow(
                    templates = self.assetsLoaderInstance.templates,
                    images = self.assetsLoaderInstance.images,
                    kit_version = kitVersion,
                    request_update_callback = self.requestUpdateCallback
                )
                # Creates the controllers and injects the windows and views
                self.windowControllerInstance = ValidatorWindowController(
                    validator_window = self.validatorWindowInstance)
            
            self.validatorWindowInstance.mainloop()
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.start_window.__name__}] "
                f"Failed to start the validator window. \n{traceBack}")
    
    def close_window(self):
        """Close the validator window"""
        try:
            self.validatorWindowInstance.destroy()
            self.validatorWindowInstance = None
            self.windowControllerInstance = None
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.close_window.__name__}] "
                f"Failed to close the validator window. \n{traceBack}")
    # ===================================
# ==============================================