import carb
import omni.usd
import omni.kit.window.file
import omni.kit.actions.core


def post_notification(message: str, info: bool = False, duration: int = 3):
    try:
        import omni.kit.notification_manager as nm
        if info:
            type = nm.NotificationStatus.INFO
        else:
            type = nm.NotificationStatus.WARNING

        nm.post_notification(message, status=type, duration=duration)
    except ModuleNotFoundError:
        carb.log_warn(message)


def quit(fast: bool = False):
    if fast:
        carb.settings.get_settings().set("/app/fastShutdown", True)
    omni.kit.app.get_app().post_quit()


def open_stage_with_new_edit_layer():
    stage = omni.usd.get_context().get_stage()
    if not stage:
        post_notification(f"Cannot Re-open with New Edit Layer. No valid stage")
        return

    omni.kit.window.file.open_with_new_edit_layer(stage.GetRootLayer().identifier)


def register_actions(extension_id):
    action_registry = omni.kit.actions.core.get_action_registry()
    actions_tag = "File Actions"

    omni.kit.actions.core.get_action_registry().register_action(
        extension_id,
        "quit",
        lambda: quit(fast=False),
        display_name="File->Exit",
        description="Exit",
        tag=actions_tag,
    )
    omni.kit.actions.core.get_action_registry().register_action(
        extension_id,
        "quit_fast",
        lambda: quit(fast=True),
        display_name="File->Exit Fast",
        description="Exit Fast",
        tag=actions_tag,
    )

    omni.kit.actions.core.get_action_registry().register_action(
        extension_id,
        "open_stage_with_new_edit_layer",
        open_stage_with_new_edit_layer,
        display_name="File->Open Current Stage With New Edit Layer",
        description="Open Stage With New Edit Layer",
        tag=actions_tag,
    )


def deregister_actions(extension_id):
    action_registry = omni.kit.actions.core.get_action_registry()
    action_registry.deregister_all_actions_for_extension(extension_id)
