use std::{collections::BTreeMap, fs::File, io::Write, path::Path};

use icu_locid::LanguageIdentifier;

use crate::{Bundle, WriteError};

pub fn export_file(bundle: &Bundle, locale: LanguageIdentifier, path: &Path) -> Result<(), WriteError> {
    let mut file = File::create(path).unwrap();
    export_fh(bundle, locale, &mut file)
}

pub fn export_fh(bundle: &Bundle, locale: LanguageIdentifier, fh: &mut File) -> Result<(), WriteError> {
    let messages = bundle.message_iter().map(|(key, message)| {
        let content = message.variant(&locale).unwrap().content().to_owned();
        (key.to_owned(), content)
    }).collect::<Vec<(String, String)>>();

    let messages: BTreeMap<String, String> = messages.into_iter().collect();
    let _ = fh.write(serde_json::to_string_pretty(&messages).unwrap().as_bytes()).unwrap();

    Ok(())
}