import os
from typing import List, Optional

import omni.client
import omni.ui as ui
from omni.kit.widget.filebrowser import LAYOUT_SINGLE_PANE_LIST, LISTVIEW_PANE, FileBrowserItem, FileBrowserModel
from omni.kit.widget.filebrowser.model import FileBrowserItemFields
from omni.kit.window.filepicker import FilePickerWidget


class RecentTableModel(FileBrowserModel):
    def __init__(self, recent_files: List[str]):
        super().__init__()
        self.refresh(recent_files)

    def get_item_children(self, item: FileBrowserItem) -> [FileBrowserItem]:
        return self._items

    def refresh(self, recent_files: List[str]):
        if recent_files:
            self._items = [self.__create_file_item(url) for url in recent_files]
        else:
            self._items = []
        self._item_changed(None)

    def __create_file_item(self, url: str) -> Optional[FileBrowserItem]:
        file_name = os.path.basename(url)
        result, entry = omni.client.stat(url)
        if result == omni.client.Result.OK:
            item = FileBrowserItem(url, FileBrowserItemFields(file_name, entry.modified_time, 0, 0), is_folder=False)
            item._models = (ui.SimpleStringModel(item.name), entry.modified_time, ui.SimpleStringModel(""))
            return item
        else:
            return None


class RecentTable:
    def __init__(self, recent_files: List[str], on_selection_changed_fn: callable):
        self.__recent_files = recent_files
        self.__picker: Optional[FilePickerWidget] = None
        self.__on_selection_changed_fn = on_selection_changed_fn
        self._build_ui()

    @property
    def selected(self) -> str:
        if self.__picker:
            selections = self.__picker._view.get_selections(pane=LISTVIEW_PANE)
            if selections:
                return selections[0].path
            else:
                return ""
        else:
            return ""

    @selected.setter
    def selected(self, url: str) -> None:
        if self.__picker:
            if url:
                for item in self._model.get_item_children(None):
                    if item.path == url:
                        selections = [item]
            else:
                selections = []
            self.__picker._view.set_selections(selections, pane=LISTVIEW_PANE)

    def refresh(self, recent_files: List[str]):
        self._model.refresh(recent_files)

    def get_filename(self) -> str:
        return self.__picker._api.get_filename() if self.__picker else ""

    def _build_ui(self):
        with ui.ZStack():
            ui.Rectangle(style_type_name_override="Stage.Separator")
            with ui.VStack():
                ui.Spacer(height=2)
                with ui.HStack():
                    self.__picker = FilePickerWidget(
                        "Welcome",
                        enable_tool_bar=False,
                        layout=LAYOUT_SINGLE_PANE_LIST,
                        show_grid_view=False,
                        save_grid_view=False,
                        enable_checkpoints=True,
                        enable_zoombar=False,
                        enable_file_bar=False,
                        selection_changed_fn=self.__on_selection_changed_fn,
                    )

                    self._model = RecentTableModel(self.__recent_files)
                    self.__picker._view.show_model(self._model)
