mod client;
mod configuration;
mod db;
mod parse;
mod server;
mod types;
mod util;

use std::{fs::File, io::Read};

use clap::Parser;
use dotenv::dotenv;

use crate::{
    client::run_client,
    configuration::{CONFIGURATION, Configuration},
    server::run_server,
    types::CallArguments,
    util::initialize_logging,
};

#[tokio::main]
async fn main() {
    dotenv().ok();
    initialize_logging("log4jrs.yaml").expect("Failed to initialize logging with log4rs");
    let cli = CallArguments::parse();
    let _config = Configuration::new().await;

    if let Err(conf) = CONFIGURATION.set(_config) {
        eprintln!("Failed to set configuration: {:?}", conf);
        return;
    }

    let _config = CONFIGURATION.get().unwrap();

    if cli.server {
        _run_server().await.expect("Failed to run server");
    } else {
        _run_client(&cli).await.expect("Failed to run client");
    }
}

async fn _run_client(cli: &CallArguments) -> Result<(), Box<dyn std::error::Error>> {
    run_client(cli).await
}

async fn _run_server() -> Result<(), Box<dyn std::error::Error>> {
    run_server().await
}

fn read(path: &str) -> Result<String, std::io::Error> {
    let mut file = File::open(path)?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}
