import carb
import omni.usd
import omni.kit.actions.core
import omni.kit.hotkeys.core

from omni.kit.hotkeys.core import KeyCombination, get_hotkey_registry
from .export_utils import ExportPrimUSD

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 save_prim(objects):
    if not objects:
        prim_list = []
        paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
        stage = omni.usd.get_context().get_stage()
        for path in paths:
            prim = stage.GetPrimAtPath(path)
            if prim:
                prim_list.append(prim)
        objects = {"prim_list":  prim_list}
    elif isinstance(objects, tuple):
        objects = objects[0]

    if not "prim_list" in objects:
        return False
    prim_list = objects["prim_list"]

    if len(prim_list) == 0:
        post_notification("Cannot save prims as no prims are selected")
    elif len(prim_list) == 1:
        ExportPrimUSD(select_msg=f"Save \"{prim_list[0].GetName()}\" As...").export(prim_list)
    else:
        ExportPrimUSD(select_msg=f"Save Prims As...").export(prim_list)


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

    omni.kit.actions.core.get_action_registry().register_action(
        extension_id,
        "save_prim",
        lambda *o: save_prim(o),
        display_name="Stage->Save Prim",
        description="Save Prim",
        tag=actions_tag,
    )

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

    hotkey_registry = get_hotkey_registry()
    for key_reg in owner._registered_hotkeys:
        hotkey_registry.deregister_hotkey(key_reg)
    owner._registered_hotkeys = []
