use std::fs::File;

use jimtcl::{Interp, JimError, JimObject, JimResult, check_or_error};
use serde::de::DeserializeSeed;

pub(crate) fn parse_yaml<'jim>(
    interp: &'jim Interp,
    args: &[JimObject<'jim>],
) -> JimResult<JimObject<'jim>> {
    let usage = "usage: parse yaml ?-file? <input>";
    check_or_error!(args.len() >= 2, usage);
    let de = if args[1].as_str()? == "-file" {
        check_or_error!(args.len() == 3, usage);
        let open = File::open(args[2].as_str()?)?;
        yaml_serde::Deserializer::from_reader(open)
    } else {
        check_or_error!(args.len() == 2, usage);
        let data = args[1].as_bytes();
        yaml_serde::Deserializer::from_slice(data)
    };

    let obj = interp.deserialize(de).map_err(JimError::wrap)?;

    Ok(obj)
}
