use super::super::framework::{NodeImpl, get_default_exec_out, eval_input_string};
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::{ComponentContext, RuntimeContext, RuntimeValue};

pub struct SetTextNode;

impl NodeImpl for SetTextNode {
    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 text = eval_input_string(graph, ctx, node.id, "text")?;
        ctx.set_text(component_name, text);
        get_default_exec_out(node)
    }
}

impl super::super::framework::NodeDescription for SetTextNode {
    fn description(&self) -> &str {
        "Sets the text content 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::String, true, "text"));
    *next_pin_id += 1;
    pins
}

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

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