import carb.settings
import omni.kit.app
from functools import partial
from ..preferences_window import PreferenceBuilder, PERSISTENT_SETTINGS_PREFIX, SettingType


class UsdSkelPreferences(PreferenceBuilder):
    def __init__(self):
        super().__init__("UsdSkel")

        self._update_setting = {}

        settings = carb.settings.get_settings()

        if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter") is None:
            settings.set_default_bool(
                PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True
            )

        if settings.get(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape") is None:
            settings.set_default_bool(
                PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape", True
            )

    def build(self):
        import omni.ui as ui

        with ui.VStack(height=0):
            with self.add_frame("UsdSkel"):
                with ui.VStack():
            
                    self.create_setting_widget(
                        "Enable BlendShape",
                        PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape",
                        SettingType.BOOL,
                        tooltip="Enable BlendShape. Will be effective on the next stage load.",
                    )

                    def _on_enable_blendshape_change(item, event_type, owner):
                        if event_type == carb.settings.ChangeEventType.CHANGED:
                            settings = carb.settings.get_settings()
                            if settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape"):
                                if not settings.get_as_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter"):
                                    settings.set_bool(PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapter", True)
                    self._update_setting["Enable BlendShape"] = omni.kit.app.SettingChangeSubscription(
                        PERSISTENT_SETTINGS_PREFIX + "/omnihydra/useSkelAdapterBlendShape",
                        partial(_on_enable_blendshape_change, owner=self),
                    )


    def __del__(self):
        super().__del__()
        self._update_setting = {}


