import omni.graph.core as og


class OgnTestReadVariablePy:
    """Python version of OgnWriteVariable"""

    @staticmethod
    def compute(db) -> bool:
        """Read the given variable and write it to the output"""

        value = db.get_variable(db.inputs.variableName)
        if value is not None:
            db.outputs.value = value
            return True
        return False

    @staticmethod
    def initialize(graph_context, node):
        function_callback = OgnTestReadVariablePy.on_value_changed_callback
        node.get_attribute("inputs:variableName").register_value_changed_callback(function_callback)

    @staticmethod
    def on_value_changed_callback(attr):
        node = attr.get_node()
        name = attr.get_attribute_data().get(False)
        var = node.get_graph().find_variable(name)
        value_attr = node.get_attribute("outputs:value")
        old_type = value_attr.get_resolved_type()
        if not var:
            value_attr.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN))
        elif var.type != old_type:
            value_attr.set_resolved_type(og.Type(og.BaseDataType.UNKNOWN))
            value_attr.set_resolved_type(var.type)
