use super::super::framework::{NodeImpl, eval_input, get_default_exec_out};
use crate::gui_builder::node_registry::{NodeSpec, ParamKind};
use crate::gui_builder::nodes::{Node, NodeCategory, NodeGraph, NodeLibrary, NodeParams, Pin, PinType};
use crate::gui_builder::interpreter::ExecutionStack;
use crate::gui_builder::runtime::{RuntimeContext, ComponentContext};

pub struct SetValueNode;

impl NodeImpl for SetValueNode {
    fn execute(&self, graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node) -> Result<Option<usize>, String> {
        let component_name = match &node.params {
            NodeParams::ComponentName(s) => s,
            _ => return Err("Missing component name".to_string()),
        };
        let value = eval_input(graph, ctx, node.id, "value")?.as_float();
        ctx.set_value(component_name, value);
        get_default_exec_out(node)
    }
}

impl super::super::framework::NodeDescription for SetValueNode {
    fn description(&self) -> &str {
        "Sets the value of a UI component."
    }
}

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

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

fn execute(graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _stack: &mut ExecutionStack) -> Result<Option<usize>, String> {
    SetValueNode.execute(graph, ctx, node)
}

crate::register_node!(NodeSpec {
    id: "SetValue",
    display_name: "Set Value",
    documentation: "Sets the value of a UI component.",
    category: NodeCategory::Action,
    library: NodeLibrary::Core,
    param_kind: ParamKind::ComponentSelector,
    default_params,
    pins,
    execute: Some(execute),
    evaluate: None,
});
