use std::fs;
use std::fs::File;
use rust_util::XResult;
use crate::credit::CreditContract;

pub fn load_credit_contract(name: &str) -> XResult<CreditContract> {
    let json = fs::read_to_string(name)?;
    serde_json::from_str(&json).map_err(|e| e.into())
}

pub fn save_credit_contract(c: &CreditContract, overwrite: bool) -> XResult<()> {
    let name = &c.name;
    if !overwrite {
        if let Ok(_) = File::open(name) {
            return simple_error!("File exists: {}", name);
        }
    }
    information!("Write file: {}", name);
    fs::write(name, serde_json::to_string(c)?.as_bytes())?;
    Ok(())
}

