use super::super::framework::EvalImpl;
use crate::gui_builder::node_registry::{NodeSpec, ParamKind};
use crate::gui_builder::nodes::{Node, NodeCategory, NodeGraph, NodeLibrary, NodeParams, Pin, PinType};
use crate::gui_builder::runtime::{RuntimeContext, RuntimeValue};

pub struct GetVariableNode;

impl EvalImpl for GetVariableNode {
    fn evaluate(&self, _graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _pin_id: usize) -> Result<RuntimeValue, String> {
        let var_name = match &node.params {
            NodeParams::VariableName(s) => s,
            _ => return Err("Missing variable name".to_string()),
        };
        
        if let Some(val) = ctx.get_variable(var_name) {
             Ok(val)
         } else {
             // Or default?
             Ok(RuntimeValue::None)
         }
    }
}

impl super::super::framework::NodeDescription for GetVariableNode {
    fn description(&self) -> &str {
        "Gets the current value of a global variable."
    }
}

fn default_params() -> NodeParams {
    NodeParams::VariableName(String::new())
}

fn pins(next_pin_id: &mut usize) -> Vec<Pin> {
    let mut pins = Vec::new();
    pins.push(Pin::new(*next_pin_id, PinType::String, false, "value"));
    *next_pin_id += 1;
    pins
}

fn evaluate(_graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, pin_id: usize) -> Result<RuntimeValue, String> {
    GetVariableNode.evaluate(_graph, ctx, node, pin_id)
}

crate::register_node!(NodeSpec {
    id: "GetVariable",
    display_name: "Get Variable",
    documentation: "Gets the current value of a global variable.",
    category: NodeCategory::Data,
    library: NodeLibrary::Core,
    param_kind: ParamKind::VariableSelector,
    default_params,
    pins,
    execute: None,
    evaluate: Some(evaluate),
});
