from typing import List

import omni.kit.app
import omni.ui as ui
from omni.ui import constant as fl

from .extensions_model import ExtensionItem, ExtensionsModel


class ExtensionCard:
    def __init__(self, item: ExtensionItem):
        self._item = item
        self._build_ui()

    def _build_ui(self):
        ICON_SIZE = 40
        with ui.ZStack(height=80):
            ui.Rectangle(style_type_name_override="Card.Background")
            with ui.HStack():
                with ui.HStack(width=250):
                    with ui.VStack(width=52):
                        ui.Spacer()
                        #with ui.Frame(height=ICON_SIZE, width=ICON_SIZE):
                        #    ui.Image(self._item.icon, style_type_name_override="Card.Icon")
                        with ui.HStack():
                            ui.Spacer()
                            ui.Image(self._item.icon, width=ICON_SIZE, height=ICON_SIZE, style_type_name_override="Card.Icon")
                            ui.Spacer()
                        ui.Label(f"v{self._item.version}", alignment=ui.Alignment.CENTER, style_type_name_override="Card.Version")
                        ui.Spacer()
                    ui.Label(self._item.name, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Name")
                with ui.ZStack():
                    ui.Label(self._item.description, alignment=ui.Alignment.LEFT_CENTER, style_type_name_override="Card.Description")
                with ui.VStack(width=130):
                    ui.Spacer()
                    ui.Button("UPDATE", height=32, style_type_name_override="Card.Button", mouse_pressed_fn=lambda x, y, b, a: self.__update())
                    ui.Spacer()

    def __update(self):
        try:
            import omni.kit.app
            manager = omni.kit.app.get_app().get_extension_manager()
            manager.set_extension_enabled_immediate("omni.kit.window.extensions", True)
            from omni.kit.window.extensions import ext_controller

            # If autoload for that one is enabled, move it to latest:
            '''
            # TODO:
            if ext_controller.is_autoload_enabled(self._item.enabled_id):
                ext_controller.toggle_autoload(self._item.enabled_id, False)
                if check_can_be_toggled(self._item.latest_id, for_autoload=True):
                    ext_controller.toggle_autoload(self._item.latest_id, True)
            '''

            # If extension is enabled, switch off to latest:
            if self._item.enabled:
                self._toggle_extension(self._item.enabled_id, False)
                self._toggle_extension(self._item.latest_id, True)
        except Exception as e:
            carb.log_warn(f"Faild to update {self._item.enabled_id} to {self._item.latest_id}: {e}")

    def _toggle_extension(self, ext_id: str, enable: bool):
        '''
        # TODO:
        if enable and not check_can_be_toggled(ext_id):
            return False
        '''
        omni.kit.commands.execute("ToggleExtension", ext_id=ext_id, enable=enable)
        return True

class ExtensionsWidget:
    def __init__(self):
        self._build_ui()

    def _build_ui(self):
        with ui.HStack():
            ui.Spacer(width=fl._find("welcome_content_padding_x"))
            with ui.VStack(spacing=5):
                with ui.HStack(height=30):
                    ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))
                    ui.Label("New Updates", style_type_name_override="Extensions.Label")
                    ui.Spacer()
                    ui.Button(
                        "CHECK FOR UPDATES",
                        width=0,
                        image_width=16,
                        spacing=4,
                        name="refresh",
                        style_type_name_override="Extensions.Button",
                        clicked_fn=self.__refresh
                    )
                    ui.Spacer(width=10)
                    ui.Button(
                        "UPDATE ALL",
                        width=0,
                        image_width=16,
                        spacing=4,
                        name="update",
                        style_type_name_override="Extensions.Button",
                        clicked_fn=self.__update_all
                    )
                    ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))

                with ui.HStack():
                    ui.Spacer(width=fl._find("welcome_extensions_scroll_size"))
                    self._model = ExtensionsModel()
                    self._frame = ui.Frame(build_fn=self._build_ext_cards)
            ui.Spacer(width=fl._find("welcome_content_padding_x"))

    def _build_exts(self):
        self._model = ExtensionsModel()
        self._frame = ui.Frame(build_fn=self._build_ext_cards)

    def _build_ext_cards(self):
        with ui.ScrollingFrame(
            horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF,
            vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED,
            style_type_name_override="Extensions.Frame"
        ):
            with ui.VStack(spacing=5):
                for item in self._model.get_item_children(None):
                    ExtensionCard(item)

    def __refresh(self):
        self._model.refresh()
        with self._frame:
            self._frame.call_build_fn()

    def __update_all(self):
        pass
