use clap::Parser;
use mkoverlay::types::OverlayDesc;
use std::path::PathBuf;
use tool_helper::{Error, exit_with_error, format_if_error, open_input, open_output};

#[derive(Parser)]
#[clap(about = "Creates a linker script and makefile part for the JabyEngine toolchain", long_about = None)]
struct CommandLine {
    #[clap(long="mk-file", help="Output path for the makefile")]
    mk_file_output: Option<PathBuf>,
    
    #[clap(long="ld-script", help="Output path for the linker script file")]
    ld_file_output: Option<PathBuf>,
    
    #[clap(value_parser, help="Input JSON for creating the files")]
    input:          Option<PathBuf>
}

fn parse_input(input: Option<PathBuf>) -> Result<OverlayDesc, Error> {
    if let Some(input) = input {
        let input = format_if_error!(open_input(&Some(input)), "Opening input file failed with: {error_text}")?;
        format_if_error!(mkoverlay::types::json_reader::read_config(input), "Parsing JSON file failed with: {error_text}")    
    }
    
    else {
        Ok(OverlayDesc::new())
    }
}

fn run_main(cmd_line: CommandLine) -> Result<(), Error> {
    let     input     = parse_input(cmd_line.input)?;
    let mut mk_output = format_if_error!(open_output(&cmd_line.mk_file_output),              "Opening file for writing makefile failed with: {error_text}")?;
    let mut ld_output = format_if_error!(open_output(&cmd_line.ld_file_output),              "Opening file for writing linkerfile failed with: {error_text}")?;

    format_if_error!(mkoverlay::creator::makefile::write(&mut mk_output, &input), "Writing makefile failed with: {error_text}")?;
    format_if_error!(mkoverlay::creator::ldscript::write(&mut ld_output, &input), "Writing ld script failed with: {error_text}")
}

fn main() {
    match CommandLine::try_parse() {
        Ok(cmd_line) => {
            match run_main(cmd_line) {
                Ok(_)      => (),
                Err(error) => exit_with_error(error)
            }
        },
        Err(error) => {
            println!("{}", error)
        }
    }
}