/*
    Copyright 2020

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
    documentation files (the "Software"), to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
    and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all copies or substantial portions
    of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
    TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
    IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
    THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

//! A small lib that help to serialize and deserialize from/to rmp (RustMessagePack) with a file.
//! It does nothing special, just encapsulates rmp_serde in two functions that can be used repeatedly.
//! ```
//! #[macro_use]
//! extern crate serde_derive;
//!
//! use rmp_fs::{save_to_rmp, load_from_rmp};
//! use std::path::Path;
//!
//! // Define a struct of data
//! #[derive(Debug, PartialEq, Deserialize, Serialize)]
//! struct ExampleData {
//!     value: i64,
//!     message: String,
//! }
//!
//! fn main() {
//!     let file_name = Path::new("test_rmp_fs.blob");
//!
//!     let data = ExampleData {
//!         value: -123456,
//!         message: "Example rmp_fs".to_string()
//!     };
//!
//!     // Save to a file it return Result<(), Box<dyn Error>>
//!     save_to_rmp(file_name, &data).expect("Fail to save as rmp.");
//!
//!     // Load from a file it return Result<T, Box<dyn Error>>
//!     let data2: ExampleData =load_from_rmp(file_name).expect("Fail to load from rmp.");
//!     println!("{:?}\n{:?}",data,data2);
//! }
//! ```

extern crate serde;
#[allow(unused_imports)]
#[macro_use]
extern crate serde_derive;
extern crate rmp_serde as rmps;


use std::error::Error;
use std::fs;
use std::fs::OpenOptions;
use std::io::{BufReader, BufWriter, Write};
use std::path::Path;

use rmps::Serializer;
use serde::Serialize;
use serde::de::DeserializeOwned;

/// Save Serializable data to a file as RustMessagePack format.
/// Note if the file already exist. **The existing file is deleted.**
/*
pub async fn save_to<T>(file : &Path, data : &T) -> Result<(), Box<dyn Error>>
    where T : Serialize{
    save_to_rmp(file,data)
}
*/

pub fn save_to_rmp<T>(file : &Path, data : &T) -> Result<(), Box<dyn Error>>
    where T : Serialize {
    if file.exists() {
        fs::remove_file(file)?;
    }
    let file_handler = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(file)?;

    let mut buf= Vec::new();
    data.serialize(&mut Serializer::new(&mut buf))?;
    let mut buf_writer = BufWriter::new(&file_handler);
    buf_writer.write_all(buf.as_slice())?;
    Ok(())
}

/// Load RustMessagePack format Deserializable data from a file.
/*
pub async fn load_from<T>(file : &Path) -> Result<T, Box<dyn Error>>
    where T : DeserializeOwned{
    load_from_rmp(file)
}
*/

pub fn load_from_rmp<T>(file : &Path) -> Result<T, Box<dyn Error>>
    where T : DeserializeOwned{
    let file_handler = OpenOptions::new()
        .read(true)
        .open(file)?;
    let buf_reader = BufReader::new(&file_handler);
    let data : T = rmps::from_read(buf_reader)?;
    Ok(data)
}

/// Tests with different type of data.
#[cfg(test)]
mod tests {
    use std::collections::{BTreeSet, HashMap};
    use std::fs;
    use std::path::Path;

    use crate::{load_from_rmp, save_to_rmp};

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    struct StructTest01 {
        text : String,
        value1 : u16,
        value2 : i32,
        value3 : u8,
        value4 : i16,
        value5 : u32,
        value6 : u64,
        value7 : i64,
        value8 : usize,
        value9 : f32,
        value10 : f64,
        array : Vec<u8>,
        tuple : (u64,u64),
        complex : StructTest02,
    }

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    struct StructTest02 {
        data_v : Vec<i16>,
        data_m : HashMap<String,String>,
        state : bool,
    }

    #[derive(Debug, PartialEq, Deserialize, Serialize)]
    enum Status {
        State1,
        State2
    }

    const TEST01_FILE: &str = "data1.rmp";
    const TEST02_FILE: &str = "data2.rmp";
    const TEST03_FILE: &str = "data3.rmp";
    const TEST04_FILE: &str = "data4.rmp";

    #[test]
    fn test_save_load_rmp_file_01() {

        let mut data_m : HashMap<String,String> =HashMap::new();
        data_m.insert("k1".into(),"V1".into());
        data_m.insert("k2".into(),"V2".into());

        let complex = StructTest02 {
            data_v: vec![-1i16;100],
            data_m,
            state: true
        };

        let data1 = StructTest01 {
            text: "Test value1 ڜڝڞڟ".to_string(),
            value1 : u16::max_value(),
            value2 : i32::min_value(),
            value3 : u8::max_value(),
            value4 : i16::min_value(),
            value5 : u32::max_value(),
            value6 : u64::max_value(),
            value7 : i64::min_value(),
            value8 : 1024 as usize,
            value9 : std::f32::INFINITY,
            value10 : std::f64::MAX,
            array: vec![0x62u8;20],
            tuple: (0x61, 0x62),
            complex
        };

        let save_result= save_to_rmp(Path::new(TEST01_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<StructTest01, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST01_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST01_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_02() {
        let data1 = Status::State1;

        let save_result= save_to_rmp(Path::new(TEST02_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<Status, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST02_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST02_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_03() {
        let data1 = 33i32;

        let save_result= save_to_rmp(Path::new(TEST03_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<i32, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST03_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST03_FILE).unwrap();
    }

    #[test]
    fn test_save_load_rmp_file_04() {
        let mut data1 : BTreeSet<String> = BTreeSet::new();

        data1.insert("Hello".into());
        data1.insert("Salut".into());
        data1.insert("Hola".into());

        let save_result= save_to_rmp(Path::new(TEST04_FILE), &data1);
        if save_result.is_err() {
            println!("{:?}",save_result.err());
            assert!(false);
        }

        let load_result : Result<BTreeSet<String>, std::boxed::Box<dyn std::error::Error>> = load_from_rmp(Path::new(TEST04_FILE));
        let data = load_result.unwrap();
        assert_eq!(&data1,&data);
        println!("{:?}",&data);
        fs::remove_file(TEST04_FILE).unwrap();
    }
}
