use super::super::framework::{NodeImpl, EvalImpl, 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::runtime::{RuntimeContext, RuntimeValue, ComponentContext};
use crate::gui_builder::interpreter::ExecutionStack;

pub struct GetComboBoxValueNode;

impl NodeImpl for GetComboBoxValueNode {
    fn execute(&self, _graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node) -> Result<Option<usize>, String> {
        let component_name = match &node.params {
            NodeParams::ComponentName(name) => name,
            _ => return Err("GetComboBoxValue node missing component name parameter".to_string()),
        };

        // Get the selected value using the trait method
        let _selected_value = ctx.get_combobox_value(component_name)
            .unwrap_or_default();

        // The value will be read from the evaluate method when needed
        get_default_exec_out(node)
    }
}

impl EvalImpl for GetComboBoxValueNode {
    fn evaluate(&self, _graph: &NodeGraph, ctx: &mut RuntimeContext, node: &Node, _pin_id: usize) -> Result<RuntimeValue, String> {
        let component_name = match &node.params {
            NodeParams::ComponentName(name) => name,
            _ => return Err("GetComboBoxValue node missing component name parameter".to_string()),
        };

        // Get the selected value using the trait method
        let selected_value = ctx.get_combobox_value(component_name)
            .unwrap_or_default();

        Ok(RuntimeValue::String(selected_value))
    }
}

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, false, "value"));
    *next_pin_id += 1;
    pins
}

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

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

crate::register_node!(NodeSpec {
    id: "GetComboBoxValue",
    display_name: "Get ComboBox Value",
    documentation: "Gets the currently selected value from a ComboBox as a string.",
    category: NodeCategory::Action,
    library: NodeLibrary::Core,
    param_kind: ParamKind::ComponentSelector,
    default_params,
    pins,
    execute: Some(exec),
    evaluate: Some(eval),
});
