extern crate pb_rs;
use pb_rs::types::{Config, FileDescriptor};
use std::path::PathBuf;
use std::io::{BufReader, BufRead, Write};
use std::fs::OpenOptions;
macro_rules! dir {
    () => {
        ::std::env::var("CARGO_MANIFEST_DIR")
            .expect("OUT_DIR is not set")
    }
}
fn main() {
    let in_file: PathBuf = (dir!() + "/src/reader.proto").into();
    let out_file: PathBuf = (dir!() + "/target/reader.rs").into();
    println!("in_file: {:?}, out_file: {:?}", in_file, out_file);
    let cfg = Config {
        in_file,
        out_file,
        single_module: true,
        import_search_path: vec![],
        no_output: false,
        error_cycle: true,
        headers: true,
        dont_use_cow: false,
        custom_includes: vec!["use serde::Serialize;".to_owned()],
        custom_struct_derive: vec!["Serialize".to_owned()],
        custom_rpc_generator: Box::new(|_, _| Ok(())),
    };

    FileDescriptor::write_proto(&cfg).expect("written protobuf");
    let out_file = String::from(dir!() + "/target/reader.rs");
    let file = OpenOptions::new().read(true).open(&out_file).expect("a file out");
    let lines = BufReader::new(file).lines().map(|s| s.expect("line")).collect::<Vec<String>>();
    let mut file_out = OpenOptions::new().write(true).truncate(true).open(&out_file).expect("a writable file");
    for line in lines {
        let new_line = match line.as_str() {
            "#[derive(Debug, PartialEq, Clone)]" => "#[derive(Serialize, Debug, PartialEq, Clone)]",
            "#[derive(Debug, PartialEq, Eq, Clone, Copy)]" => "use super::*;\n#[derive(Serialize, Debug, PartialEq, Eq, Clone, Copy)]",
            s => s
        };
        writeln!(file_out, "{}", new_line).expect("to write a line");
    }
}
