import functools
import locale
from typing import List

import omni.kit.stage_templates
import omni.ui as ui
from omni.kit.welcome.window import show_window

from .style import ICON_PATH
from .thumbnail_grid import ThumbnailGrid, ThumbnailItem, ThumbnailModel
import asyncio


class TemplateItem(ThumbnailItem):
    """
    Data item for template.
    """
    def __init__(self, template: list):
        # TODO: how to get template thumbnail?
        stage_name = template[0]
        super().__init__("", stage_name)

    def execute(self):
        from .open_action import run_open_action
        run_open_action("omni.kit.stage.templates", self.__get_action_name())

    def __get_action_name(self):
        return "create_new_stage_" + self.url.lower().replace('-', '_').replace(' ', '_')


class TemplateModel(ThumbnailModel):
    """
    Data model for templates.
    """
    def __init__(self):
        stage_templates = omni.kit.stage_templates.get_stage_template_list()
        template_items: List[ThumbnailItem] = []

        def sort_cmp(template1, template2):
            return locale.strcoll(template1[0], template2[0])

        for template_list in stage_templates:
            for template in sorted(template_list.items(), key=functools.cmp_to_key(sort_cmp)):
                template_items.append(TemplateItem(template))

        super().__init__(template_items)


class TemplateGrid(ThumbnailGrid):
    """
    Template grid.
    """
    def __init__(self, **kwargs):
        self._model = TemplateModel()
        super().__init__(self._model, **kwargs)

    def build_thumbnail(self, item: ThumbnailItem):
        padding = 5
        with ui.ZStack():
            super().build_thumbnail(item)
            with ui.VStack():
                ui.Spacer()
                with ui.HStack(height=20):
                    ui.Spacer()
                    ui.Image(
                        f"{ICON_PATH}/add_dark.svg",
                        width=20,
                        style_type_name_override="Template.Add",
                        mouse_pressed_fn=lambda x, y, a, f, i=item: i.execute()
                    )
                    ui.Spacer(width=padding)
                ui.Spacer(height=padding)