use siphan::{decode, Encode, EncodeFrom, EncodeResult};
use std::fs::File;
use std::io::prelude::*;

fn main() {
    encrypt_file(
        "examples/test.txt",
        "examples/output.txt",
        "examples/key.txt",
    );

    decrypt_file(
        "examples/output.txt",
        "examples/key.txt",
        "examples/origin.txt",
    );
}

fn encrypt_file(from: &str, to: &str, key: &str) {
    let mut content = String::new();
    let mut f = File::open(from).unwrap();
    f.read_to_string(&mut content).unwrap();

    let content = Encode::new().encode_from(content);

    let mut f = File::create(to).unwrap();
    f.write(content.val.as_bytes()).unwrap();

    let mut f = File::create(key).unwrap();
    f.write(content.key.as_bytes()).unwrap();
}

fn decrypt_file(a: &str, b: &str, c: &str) {
    let (mut val, mut key) = (String::new(), String::new());
    let mut f = File::open(a).unwrap();
    f.read_to_string(&mut val).unwrap();

    let mut f = File::open(b).unwrap();
    f.read_to_string(&mut key).unwrap();

    let e = EncodeResult::set_kv(key, val);
    let content = decode(&e).unwrap();

    let mut f = File::create(c).unwrap();
    f.write(content.as_bytes()).unwrap();
}
