Thunderstore CLI and Northstar mod dev helper
pub(crate) const FILE_NAME: &str = "mrvn.ron";
mod model;
mod vcs;

use std::{collections::HashMap, fs, path::Path};

use crate::core::{
    model::{Manifest, ScriptObj},
    vcs::init_vcs,
};

use log::{debug, error, trace};

use self::{model::Mod, vcs::Vcs};

///Create a mod in a new directory
pub fn create(author: String, name: String, vcs: bool) {
    let root = std::env::current_dir().unwrap();
    let mod_dir = root.join(format!("{}.{}", author, name));
    let vcs = if vcs { Vcs::None } else { Vcs::Git };
    init_mod(&mod_dir, &name, vcs);
    let mrvn = Mod::new(author, name);
    mrvn.save().expect("Failed to write tracking file");
}

pub fn init(name: String) {
    let root = std::env::current_dir().unwrap();
    init_mod(&root, &name);
}
pub fn init(author: String, name: String, vcs: bool) {
    let root = std::env::current_dir().unwrap();
    let vcs = if vcs { Vcs::None } else { Vcs::Git };
    init_mod(&root, &name, vcs);
    let mrvn = Mod::new(author, name);
    mrvn.save().expect("Failed to write tracking file");
}

fn init_mod(path: &Path, name: &str, vcs: Vcs) {
    //create dir
    debug!("Creating directory at {}", path.display());
    if let Err(e) = fs::create_dir_all(&path) {
        error!("Failed to create new mod directory: {}", e);
    }

    //change to the directory for mrvn.ron stuff
    trace!("Change directory to {}", path.display());
    if let Err(e) = std::env::set_current_dir(path) {
        error!("Couldn't change directory to {}: {}", path.display(), e);
    }

    //create git repo
    debug!("Initializing version control");
    if let Err(e) = init_vcs(&vcs, &path) {
        error!("Failed to initialize repository: {}", e);
    }

    //create boilerplate
    debug!("Create mod.json");
    let mut mo = Manifest::new(name.to_owned(), String::new());

    let example = include_str!("example_mod");

    let mut map = HashMap::new();
    map.insert("After".to_owned(), "MRVN_Example".to_owned());
    let scrobj = ScriptObj {
        path: "example.nut".to_owned(),
        run_on: "( CLIENT || SERVER ) && MP".to_owned(),
        server_callback: None,
        client_callback: Some(map),
    };

    mo.scripts.push(scrobj);
    let path = path.join("mod").join("scripts").join("vscripts");
    fs::create_dir_all(&path).unwrap();
    fs::write(path.join("example.nut"), example).unwrap();

    mo.save().unwrap();
}