import traceback

from shared.utils import Logger, AssetLoader
from shared.contracts import UpdateDoneCallback
from updater.src.ui.updater_window import UpdaterWindow

# =============== Updater App ===============
class UpdaterApp():
    def __init__(self, update_done: UpdateDoneCallback, kit_url: str):
        # Logger
        self.logger = Logger.create_logger(logger_name = "Update App", log_file_name = "update_app")
        # Callback Functions
        self.updateDoneCallback: UpdateDoneCallback = update_done

        # Helper Classes Instances
        self.assetLoader: AssetLoader | None = None
        self.updaterWindowInstance: UpdaterWindow | None = None
        
        # Kit URL
        self.kitUrl = kit_url
        
    # ========== Functionality ==========
    def start_window(self) -> None:
        """Start the updater window"""
        try:
            if self.updaterWindowInstance is None:
                self.assetLoader = AssetLoader(template_type = "Updater")
                self.updaterWindowInstance = UpdaterWindow(
                    templates = self.assetLoader.templates,
                    images = self.assetLoader.images,
                    update_done_callback = self.updateDoneCallback,
                    kit_url = self.kitUrl)
            
            self.updaterWindowInstance.mainloop()
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.start_window.__name__}] "
                f"Failed to start the updater window. \n{traceBack}")
    
    def close_window(self) -> None:
        try:
            self.assetLoader = None
            self.updaterWindowInstance.destroy()
            self.updaterWindowInstance = None
        except:
            traceBack = traceback.format_exc()
            self.logger.error(
                f"[{self.__class__.__name__} - {self.close_window.__name__}] "
                f"Failed to stop the updater window. \n{traceBack}")
    # ===================================
# ===========================================