use std::rc::Rc;

use crate::{
    error::MachineError,
    vm::{
        Value,
        env::Environment,
        value::{StringValue, convert::TryFromValue},
    },
};

pub fn load(env: &Rc<Environment>) {
    env.defun_native(
        "split",
        "Splits a string by given separator",
        |_, _, args| {
            let (separator, string) = match args {
                [string] => (&StringValue::from(" "), string),
                [separator, string] => (&StringValue::try_from_value(separator)?, string),
                _ => return Err(MachineError::InvalidArgumentCount),
            };
            let string = StringValue::try_from_value(string)?;
            let mut items = Value::Nil;
            for item in string.rsplit(&**separator) {
                items = Value::String(item.into()).cons(items);
            }
            Ok(items)
        },
    );
}
