import omni
import os

from omni.kit.widget.prompt import PromptManager, PromptButtonInfo
from .omni_client_wrapper import OmniClientWrapper
from .filebrowser import FileBrowserMode
from .filebrowser.app_filebrowser import FileBrowserUI


class FilePicker:
    def __init__(self, title, mode, file_type, filter_options, ok_button_title="Open"):
        self._mode = mode
        self._app = omni.kit.app.get_app()
        self._open_handler = None
        self._cancel_handler = None
        self._ui_handler = FileBrowserUI(title, mode, file_type, filter_options, ok_button_title)

    def _show_prompt(self, file_path, file_save_handler):
        def on_confirm():
            if file_save_handler:
                file_save_handler(file_path)

        PromptManager.post_simple_prompt(
            f'{omni.kit.ui.get_custom_glyph_code("${glyphs}/exclamation.svg")} Overwrite',
            f"File {os.path.basename(file_path)} already exists, do you want to overwrite it?",
            PromptButtonInfo("Confirm", on_confirm),
            PromptButtonInfo("Cancel")
        )

    def _save_and_prompt_if_exists(self, file_path, file_save_handler=None):
        existed = OmniClientWrapper.exists_sync(file_path)
        if existed:
            self._show_prompt(file_path, file_save_handler)
        elif file_save_handler:
            file_save_handler(file_path)

    def _on_file_open(self, path):
        if self._mode == FileBrowserMode.SAVE:
            self._save_and_prompt_if_exists(path, self._open_handler)
        elif self._open_handler:
            self._open_handler(path)

    def _on_cancel_open(self):
        if self._cancel_handler:
            self._cancel_handler()

    def set_file_selected_fn(self, file_open_handler):
        self._open_handler = file_open_handler

    def set_cancel_fn(self, cancel_handler):
        self._cancel_handler = cancel_handler

    def show(self, dir=None, filename=None):
        if self._ui_handler:
            if dir and OmniClientWrapper.exists_sync(dir):
                self._ui_handler.set_current_directory(dir)

            if filename:
                self._ui_handler.set_current_filename(filename)
            self._ui_handler.open(self._on_file_open, self._on_cancel_open)

    def set_current_directory(self, dir):
        if self._ui_handler:
            if dir and OmniClientWrapper.exists_sync(dir):
                self._ui_handler.set_current_directory(dir)

    def set_current_filename(self, filename):
        if self._ui_handler:
            self._ui_handler.set_current_filename(filename)

    def set_filebar_label_name(self, name):
        if self._ui_handler:
            self._ui_handler.set_filebar_label_name(name)

    def destroy(self):
        self._open_handler = None
        self._cancel_handler = None

        if self._ui_handler:
            self._ui_handler.destroy()
        self._ui_handler = None
