use std::{borrow::Cow, fs::read_to_string};

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

pub(crate) fn parse_toml<'jim>(
    interp: &'jim Interp,
    args: &[JimObject<'jim>],
) -> JimResult<JimObject<'jim>> {
    let usage = "usage: parse toml ?-file? <input>";
    check_or_error!(args.len() >= 2, usage);
    let data: Cow<'_, str> = if args[1].as_str()? == "-file" {
        check_or_error!(args.len() == 3, usage);
        read_to_string(args[2].as_str()?)?.into()
    } else {
        check_or_error!(args.len() == 2, usage);
        args[1].as_str()?.into()
    };

    let de = toml::Deserializer::parse(&data).map_err(JimError::wrap)?;
    let obj = interp.deserialize(de).map_err(JimError::wrap)?;

    Ok(obj)
}
