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


class TaggingPreferences(PreferenceBuilder):
    def __init__(self):
        super().__init__("Tagging")

        self._showAdvanced = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showAdvancedTagView"
        self._showHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/showHiddenTags"
        self._modifyHidden = PERSISTENT_SETTINGS_PREFIX + "/exts/omni.kit.property.tagging/modifyHiddenTags"

        carb.settings.get_settings().set_default_bool(self._showAdvanced, False)
        carb.settings.get_settings().set_default_bool(self._showHidden, False)
        carb.settings.get_settings().set_default_bool(self._modifyHidden, False)

    def build(self):
        # update on setting change
        def _on_change(item, event_type, owner):
            if event_type == carb.settings.ChangeEventType.CHANGED:
                owner._update_visibility()

        self._update_setting = omni.kit.app.SettingChangeSubscription(
            self._showAdvanced, partial(_on_change, owner=self)
        )
        self._update_setting2 = omni.kit.app.SettingChangeSubscription(
            self._showHidden, partial(_on_change, owner=self)
        )

        """ Tagging """
        with ui.VStack(height=0):
            with self.add_frame("Tagging"):
                with ui.VStack():
                    self.create_setting_widget("Allow advanced tag view", self._showAdvanced, SettingType.BOOL)
                    self._showHiddenWidget = self.create_setting_widget(
                        "Show hidden tags in advanced view", self._showHidden, SettingType.BOOL
                    )
                    self._modifyHiddenWidget = self.create_setting_widget(
                        "Allow adding and modifying hidden tags directly", self._modifyHidden, SettingType.BOOL
                    )

        self._update_visibility()

    def _update_visibility(self):
        settings = carb.settings.get_settings()

        if settings.get_as_bool(self._showAdvanced):
            self._showHiddenWidget.enabled = True
            self._modifyHiddenWidget.enabled = settings.get_as_bool(self._showHidden)
        else:
            self._showHiddenWidget.enabled = False
            self._modifyHiddenWidget.enabled = False
