"""Support for simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributesPy

This is a Python node that exercises the ability to add and remove database attribute accessors for dynamic attributes. When
the dynamic attribute is added the property will exist and be able to get/set the attribute values. When it does not the
property will not exist. The dynamic attribute names are found in the tokens below. If neither exist then the input value
is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input is x-ored for the copy. If
'secondBit' exists then the 'secondBit'th bit of the input is x-ored for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1,
xor(1,0)=1, and xor(1,1)=0.) For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit
1 is set. If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result. If on
the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit 2 is set. The input of 7
(b0111) flips bit 1 because firstBit=1 and flips bit 2 because secondBit=2, yielding a final result of 1 (b0001).
"""

import carb
import sys
import traceback

import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn



class OgnTutorialDynamicAttributesPyDatabase(og.Database):
    """Helper class providing simplified access to data on nodes of type omni.graph.tutorials.DynamicAttributesPy

    Class Members:
        node: Node being evaluated

    Attribute Value Properties:
        Inputs:
            inputs.value
        Outputs:
            outputs.result

    Predefined Tokens:
        tokens.firstBit
        tokens.secondBit
        tokens.invert
    """

    # Imprint the generator and target ABI versions in the file for JIT generation
    GENERATOR_VERSION = (1, 41, 3)
    TARGET_VERSION = (2, 139, 12)

    # This is an internal object that provides per-class storage of a per-node data dictionary
    PER_NODE_DATA = {}

    # This is an internal object that describes unchanging attributes in a generic way
    # The values in this list are in no particular order, as a per-attribute tuple
    #     Name, Type, ExtendedTypeIndex, UiName, Description, Metadata,
    #     Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg
    # You should not need to access any of this data directly, use the defined database interfaces
    INTERFACE = og.Database._get_interface([
        ('inputs:value', 'uint', 0, None, 'Original value to be modified.', {}, True, 0, False, ''),
        ('outputs:result', 'uint', 0, None, 'Modified value', {}, True, None, False, ''),
    ])

    class tokens:
        firstBit = "inputs:firstBit"
        secondBit = "inputs:secondBit"
        invert = "inputs:invert"

    class ValuesForInputs(og.DynamicAttributeAccess):
        LOCAL_PROPERTY_NAMES = {"value", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"}
        """Helper class that creates natural hierarchical access to input attributes"""
        def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
            """Initialize simplified access for the attribute data"""
            context = node.get_graph().get_default_graph_context()
            super().__init__(context, node, attributes, dynamic_attributes)
            self._batchedReadAttributes = [self._attributes.value]
            self._batchedReadValues = [0]

        @property
        def value(self):
            return self._batchedReadValues[0]

        @value.setter
        def value(self, value):
            self._batchedReadValues[0] = value

        def __getattr__(self, item: str):
            if item in self.LOCAL_PROPERTY_NAMES:
                return object.__getattribute__(self, item)
            else:
                return super().__getattr__(item)

        def __setattr__(self, item: str, new_value):
            if item in self.LOCAL_PROPERTY_NAMES:
                object.__setattr__(self, item, new_value)
            else:
                super().__setattr__(item, new_value)

        def _prefetch(self):
            readAttributes = self._batchedReadAttributes
            newValues = _og._prefetch_input_attributes_data(readAttributes)
            if len(readAttributes) == len(newValues):
                self._batchedReadValues = newValues

    class ValuesForOutputs(og.DynamicAttributeAccess):
        LOCAL_PROPERTY_NAMES = {"result", "_batchedWriteValues"}
        """Helper class that creates natural hierarchical access to output attributes"""
        def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
            """Initialize simplified access for the attribute data"""
            context = node.get_graph().get_default_graph_context()
            super().__init__(context, node, attributes, dynamic_attributes)
            self._batchedWriteValues = { }

        @property
        def result(self):
            value = self._batchedWriteValues.get(self._attributes.result)
            if value:
                return value
            else:
                data_view = og.AttributeValueHelper(self._attributes.result)
                return data_view.get()

        @result.setter
        def result(self, value):
            self._batchedWriteValues[self._attributes.result] = value

        def __getattr__(self, item: str):
            if item in self.LOCAL_PROPERTY_NAMES:
                return object.__getattribute__(self, item)
            else:
                return super().__getattr__(item)

        def __setattr__(self, item: str, new_value):
            if item in self.LOCAL_PROPERTY_NAMES:
                object.__setattr__(self, item, new_value)
            else:
                super().__setattr__(item, new_value)

        def _commit(self):
            _og._commit_output_attributes_data(self._batchedWriteValues)
            self._batchedWriteValues = { }

    class ValuesForState(og.DynamicAttributeAccess):
        """Helper class that creates natural hierarchical access to state attributes"""
        def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface):
            """Initialize simplified access for the attribute data"""
            context = node.get_graph().get_default_graph_context()
            super().__init__(context, node, attributes, dynamic_attributes)

    def __init__(self, node):
        super().__init__(node)
        dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT)
        self.inputs = OgnTutorialDynamicAttributesPyDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
        dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
        self.outputs = OgnTutorialDynamicAttributesPyDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
        dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
        self.state = OgnTutorialDynamicAttributesPyDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)

    class abi:
        """Class defining the ABI interface for the node type"""

        @staticmethod
        def get_node_type():
            get_node_type_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
            if callable(get_node_type_function):
                return get_node_type_function()
            return 'omni.graph.tutorials.DynamicAttributesPy'

        @staticmethod
        def compute(context, node):
            def database_valid():
                return True
            try:
                per_node_data = OgnTutorialDynamicAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
                db = per_node_data.get('_db')
                if db is None:
                    db = OgnTutorialDynamicAttributesPyDatabase(node)
                    per_node_data['_db'] = db
                if not database_valid():
                    per_node_data['_db'] = None
                    return False
            except:
                db = OgnTutorialDynamicAttributesPyDatabase(node)

            try:
                compute_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'compute', None)
                if callable(compute_function) and compute_function.__code__.co_argcount > 1:
                    return compute_function(context, node)

                db.inputs._prefetch()
                db.inputs._setting_locked = True
                with og.in_compute():
                    return OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS.compute(db)
            except Exception as error:
                stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next))
                db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False)
            finally:
                db.inputs._setting_locked = False
                db.outputs._commit()
            return False

        @staticmethod
        def initialize(context, node):
            OgnTutorialDynamicAttributesPyDatabase._initialize_per_node_data(node)
            initialize_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize', None)
            if callable(initialize_function):
                initialize_function(context, node)

            per_node_data = OgnTutorialDynamicAttributesPyDatabase.PER_NODE_DATA[node.node_id()]
            def on_connection_or_disconnection(*args):
                per_node_data['_db'] = None

            node.register_on_connected_callback(on_connection_or_disconnection)
            node.register_on_disconnected_callback(on_connection_or_disconnection)

        @staticmethod
        def release(node):
            release_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'release', None)
            if callable(release_function):
                release_function(node)
            OgnTutorialDynamicAttributesPyDatabase._release_per_node_data(node)

        @staticmethod
        def release_instance(node, target):
            OgnTutorialDynamicAttributesPyDatabase._release_per_node_instance_data(node, target)

        @staticmethod
        def update_node_version(context, node, old_version, new_version):
            update_node_version_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'update_node_version', None)
            if callable(update_node_version_function):
                return update_node_version_function(context, node, old_version, new_version)
            return False

        @staticmethod
        def initialize_type(node_type):
            initialize_type_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'initialize_type', None)
            needs_initializing = True
            if callable(initialize_type_function):
                needs_initializing = initialize_type_function(node_type)
            if needs_initializing:
                node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.graph.tutorials")
                node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Tutorial Python Node: Dynamic Attributes")
                node_type.set_metadata(ogn.MetadataKeys.TOKENS, "{\"firstBit\": \"inputs:firstBit\", \"secondBit\": \"inputs:secondBit\", \"invert\": \"inputs:invert\"}")
                node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "tutorials")
                node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "This is a Python node that exercises the ability to add and remove database attribute accessors for dynamic attributes. When the dynamic attribute is added the property will exist and be able to get/set the attribute values. When it does not the property will not exist. The dynamic attribute names are found in the tokens below. If neither exist then the input value is copied to the output directly. If 'firstBit' exists then the 'firstBit'th bit of the input is x-ored for the copy. If 'secondBit' exists then the 'secondBit'th bit of the input is x-ored for the copy. (Recall bitwise match xor(0,0)=0, xor(0,1)=1, xor(1,0)=1, and xor(1,1)=0.) For example, if 'firstBit' is present and set to 1 then the bitmask will be b0010, where bit 1 is set. If the input is 7, or b0111, then the xor operation will flip bit 1, yielding b0101, or 5 as the result. If on the next run 'secondBit' is also present and set to 2 then its bitmask will be b0100, where bit 2 is set. The input of 7 (b0111) flips bit 1 because firstBit=1 and flips bit 2 because secondBit=2, yielding a final result of 1 (b0001).")
                node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
                icon_path = carb.tokens.get_tokens_interface().resolve("${omni.graph.tutorials}")
                icon_path = icon_path + '/' + "ogn/icons/omni.graph.tutorials.DynamicAttributesPy.svg"
                node_type.set_metadata(ogn.MetadataKeys.ICON_PATH, icon_path)
                OgnTutorialDynamicAttributesPyDatabase.INTERFACE.add_to_node_type(node_type)

        @staticmethod
        def on_connection_type_resolve(node):
            on_connection_type_resolve_function = getattr(OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None)
            if callable(on_connection_type_resolve_function):
                on_connection_type_resolve_function(node)

    NODE_TYPE_CLASS = None

    @staticmethod
    def register(node_type_class):
        OgnTutorialDynamicAttributesPyDatabase.NODE_TYPE_CLASS = node_type_class
        og.register_node_type(OgnTutorialDynamicAttributesPyDatabase.abi, 1)

    @staticmethod
    def deregister():
        og.deregister_node_type("omni.graph.tutorials.DynamicAttributesPy")
