from typing import Callable

import carb
import omni.kit.app
import omni.ui as ui


class WelcomePageItem(ui.AbstractItem):
    def __init__(self, raw_data: dict):
        super().__init__()
        self.text = raw_data.get("text", "")
        self.icon = raw_data.get("icon", "")
        self.active_icon = raw_data.get("active_icon", self.icon)
        self.extension_id = raw_data.get("extension_id")
        self.order = raw_data.get("order", 0xFFFFFFFF)
        self.build_fn: Callable[[None], None] = None
        carb.log_info(f"Register welcome page: {self}")

    def build_ui(self) -> None:
        # Enable page extension and call build_ui
        manager = omni.kit.app.get_app().get_extension_manager()
        manager.set_extension_enabled_immediate(self.extension_id, True)
        try:
            if self.build_fn:
                self.build_fn()
            else:
                carb.log_error(f"Failed to build page for `{self.text}` because build entry point not defined!")
        except Exception as e:
            carb.log_error(f"Failed to build page for `{self.text}`: {e}")

    def __repr__(self):
        return f"{self.text}:{self.extension_id}"