from typing import cast
from webview import Window, active_window
from . import context
from .window_proxy import AsyncAwareWindowWrapper


def get_active_window() -> Window:
    """Get the currently active webview window.

    Retrieves the webview window instance that is currently active and focused.
    This is useful for operations that need to interact with the window that
    the user is currently interacting with.

    Example:
    .. code-block:: python
        from instaui import ui, html, webview_context
        import webview

        @ui.page("/")
        def index_page():
            selected_file = ui.state("")

            @ui.event(outputs=[selected_file])
            def select_file():
                return webview_context.get_active_window().create_file_dialog(webview.FileDialog.OPEN)[0]
    """
    window = active_window()
    assert window is not None
    return cast(Window, AsyncAwareWindowWrapper(window))


def get_launcher():
    """Get the webview launcher object.

    Example:
    .. code-block:: python
        from instaui import ui, html, webview_context

        @ui.page("/")
        def index_page():
            selected_file = ui.state("")

            @ui.event(outputs=[selected_file])
            def to_about():
                webview_context.get_launcher().create_window("/about")

        @ui.page("/about")
        def about_page():
            html.p("About Page")
    """

    return context.get_context().launcher


def get_async_executor():
    """Get the async executor object.

    Example:
    .. code-block:: python
        from instaui import ui, html, webview_context

        @ui.page("/")
        def index_page():
            ...

        wv = ui.webview(auto_create_window=False)
        window = wv.create_window("/")

        def on_closing():
            webview_context.get_async_executor().run_and_wait(AppContainer.tear_down())

        window.events.closing += on_closing

        wv.run()
    """
    return context.get_context().launcher.launch_config.async_executor
