use super::super::framework::{EvalImpl, eval_input, 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::runtime::{RuntimeContext, RuntimeValue};

pub struct JsonArrayToStringNode;

impl EvalImpl for JsonArrayToStringNode {
    fn evaluate(&self, graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _pin_id: usize) -> Result<RuntimeValue, String> {
        let array_val = eval_input(graph, ctx, node.id, "array")?;
        let delimiter = eval_input_string(graph, ctx, node.id, "delimiter")?;
        
        // Default delimiter is comma if empty
        let delim = if delimiter.is_empty() { "," } else { &delimiter };
        
        let result = match array_val {
            RuntimeValue::Array(arr) => {
                let strings: Vec<String> = arr.iter().map(|v| v.as_string()).collect();
                strings.join(delim)
            },
            _ => String::new(),
        };
        
        Ok(RuntimeValue::String(result))
    }
}

impl super::super::framework::NodeDescription for JsonArrayToStringNode {
    fn description(&self) -> &str {
        "Converts an array back to a delimited string (e.g., comma-separated)."
    }
}

fn default_params() -> NodeParams {
    NodeParams::None
}

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

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

crate::register_node!(NodeSpec {
    id: "JsonArrayToString",
    display_name: "Array To String",
    documentation: "Converts an array back to a delimited string (e.g., comma-separated).",
    category: NodeCategory::Data,
    library: NodeLibrary::Json,
    param_kind: ParamKind::None,
    default_params,
    pins,
    execute: None,
    evaluate: Some(eval),
});
