# Copyright (c) 2021, NVIDIA CORPORATION.  All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto.  Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["Hotkey"]

from functools import partial
import carb.input
import omni.appwindow


class Hotkey:
    """
    Bind a hotkey to the given callback. The hotkey is active while the
    object is alive.
    """

    def __init__(self, action_name, hotkey, modifier, on_action_fn):
        self._input = carb.input.acquire_input_interface()
        settings = carb.settings.get_settings()

        # TODO: bind to all app windows
        appwindow = omni.appwindow.get_default_app_window()
        action_mapping_set_path = appwindow.get_action_mapping_set_path()
        action_mapping_set = self._input.get_action_mapping_set_by_path(action_mapping_set_path)

        input_string = carb.input.get_string_from_action_mapping_desc(hotkey, modifier)
        input_path = action_mapping_set_path + "/" + action_name + "/0"
        settings.set_default_string(input_path, input_string)

        def action_trigger(on_action_fn, evt, *_):
            if not evt.flags & carb.input.BUTTON_FLAG_PRESSED:
                return

            on_action_fn()

        self._sub = self._input.subscribe_to_action_events(
            action_mapping_set, action_name, partial(action_trigger, on_action_fn)
        )

    def __del__(self):
        self._input.unsubscribe_to_action_events(self._sub)
