
__all__ = ["InspectorTreeDelegate"]

import os.path
import omni.ui as ui
import omni.kit.app
import carb
from .inspector_tree_model import WidgetItem, InspectorTreeModel
from pathlib import Path

ICON_PATH = Path(__file__).parent.parent.parent.parent.parent.parent.joinpath("icons")


class InspectorTreeDelegate(ui.AbstractItemDelegate):
    def __init__(self):
        super().__init__()

        self._context_menu = None
        self._window_title = None
        self._icon_alternatives = {
            "CollapsableFrame": "Frame",
            "InvisibleButton": "Button",
            "ImageWithProvider": "Image",
            "FloatDrag": "FloatField",
        }

    def set_window(self, window: ui.Window):
        if window:
            self._window_title = window.title

    def _copy_path(self, item: WidgetItem):
        try:
            import omni.kit.clipboard

            omni.kit.clipboard.copy(item.path)
        except ImportError:
            carb.log_warn("Could not import omni.kit.clipboard.")

    def _expand_nodes(self, item: WidgetItem, expand=False):
        from ..inspector_widget import INSPECTOR_ITEM_EXPANDED_ID

        stream = omni.kit.app.get_app().get_message_bus_event_stream()
        stream.push(INSPECTOR_ITEM_EXPANDED_ID, payload={"item_path": item.path, "expand": expand})

    def _show_context_menu(self, button: int, item: WidgetItem):
        if not self._context_menu:
            self._context_menu = ui.Menu("Context")

        self._context_menu.clear()

        if not button == 1:
            return

        def send_selected_message(item: WidgetItem):
            from ..inspector_widget import INSPECTOR_PREVIEW_CHANGED_ID

            stream = omni.kit.app.get_app().get_message_bus_event_stream()
            stream.push(
                INSPECTOR_PREVIEW_CHANGED_ID, payload={"item_path": item.path, "window_name": self._window_title}
            )

        with self._context_menu:
            ui.MenuItem("Preview", triggered_fn=lambda item=item: send_selected_message(item))
            ui.MenuItem("Copy Path", triggered_fn=lambda item=item: self._copy_path(item))
            if item.expanded:
                ui.MenuItem(
                    "Collapse All", triggered_fn=lambda item=item, expand=False: self._expand_nodes(item, expand)
                )
            else:
                ui.MenuItem("Expand All", triggered_fn=lambda item=item, expand=True: self._expand_nodes(item, expand))

        self._context_menu.show()

    def build_branch(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
        """Create a branch widget that opens or closes subtree"""
        if column_id == 0:
            with ui.HStack(width=25 * (level + 1), height=0, style={"Line": {"color": 0xFFAAAAAA}}):
                ui.Spacer(width=25 * level + 10)

                if model.can_item_have_children(item):
                    # ui.Spacer()
                    with ui.VStack():
                        ui.Spacer()
                        image_name = "Minus" if expanded else "Plus"
                        ui.Image(f"{ICON_PATH}/{image_name}.svg", width=10, height=10, style={"color": 0xFFCCCCCC})
                        ui.Spacer()
                else:
                    ui.Spacer(width=10)
                ui.Spacer()

    def build_widget(self, model: InspectorTreeModel, item: WidgetItem, column_id, level, expanded):
        """Create a widget per column per item"""
        value_model: ui.AbstractValueModel = model.get_item_value_model(item, column_id)
        widget_type = model.get_widget_type(item)

        if column_id == 0:
            with ui.HStack(height=30, mouse_pressed_fn=lambda x, y, b, m, item=item: self._show_context_menu(b, item)):
                with ui.VStack(width=25):
                    ui.Spacer()
                    icon = f"{widget_type}"
                    if not os.path.isfile(f"{ICON_PATH}/{icon}.svg"):
                        if icon in self._icon_alternatives:
                            icon = self._icon_alternatives[icon]
                        else:
                            carb.log_warn(f"{ICON_PATH}/{icon}.svg not found")
                            icon = "Missing"
                    ui.Image(f"{ICON_PATH}/{icon}.svg", width=25, height=25)
                    ui.Spacer()
                ui.Spacer(width=10)
                with ui.VStack():
                    ui.Spacer()
                    ui.Label(
                        value_model.as_string,
                        height=0,
                        style={"color": 0xFFEEEEEE},
                        tooltip=model.get_widget_path(item),
                    )
                    ui.Spacer()
        elif column_id == 1:
            # does it contain a Local Style
            if value_model.as_bool:
                with ui.HStack():
                    ui.Label("Style", alignment=ui.Alignment.RIGHT)
                    ui.Spacer(width=5)

    def build_header(self, column_id):
        """Create a widget per column per item"""
        label = ""
        if column_id == 0:
            label = "Type"

        if column_id == 1:
            label = "Has Style"

        ui.Label(label, alignment=ui.Alignment.CENTER)
