use serde::{Serialize, Deserialize};
use serde_json::Number;
use serde_json::map::Map;
use serde_json::Value as JsonValue;
use serde_hjson::Value as HJsonValue;

#[derive(Serialize, Deserialize, Debug)]
struct Config {
    id: f64,
    name: String,
}

fn main() {
    let confing_str = r#"
    {
        id: 111 // id
        name: "hatter jiang" // name
    }
"#;
    // let c: Config = serde_hjson::from_str(confing_str).unwrap(); // why not works?
    let c: HJsonValue = serde_hjson::from_str(confing_str).unwrap();
    println!("{:#?}", &c);
    println!("{}", serde_json::to_string_pretty(&map(&c)).unwrap());
    let cc: Config = serde_json::from_str(&serde_json::to_string_pretty(&map(&c)).unwrap()).unwrap();
    println!("{}", serde_json::to_string_pretty(&cc).unwrap());
}

fn map(c: &HJsonValue) -> JsonValue {
    match c {
        HJsonValue::Array(a) => {
            let mut aa = vec![];
            for x in a.iter() {
                aa.push(map(x));
            }
            JsonValue::Array(aa)
        }
        HJsonValue::Bool(b) => JsonValue::Bool(*b),
        HJsonValue::F64(f) => JsonValue::Number(Number::from_f64(*f).unwrap()),
        HJsonValue::I64(i) => JsonValue::Number(Number::from_f64(*i as f64).unwrap()),
        HJsonValue::Null => JsonValue::Null,
        HJsonValue::Object(o) => {
            let mut mm = Map::new();
            for (k, v) in o.iter() {
                mm.insert(k.to_owned(), map(v));
            }
            JsonValue::Object(mm)
        },
        HJsonValue::String(s) => JsonValue::String(s.to_owned()),
        HJsonValue::U64(u) => JsonValue::Number(Number::from_f64(*u as f64).unwrap()),
    }
}
