let fs = require('fs');
let proc = require('child_process');
const pergen = 9;
const generation = "4";
var foods = JSON.parse(fs.readFileSync('generated/3.json', 'utf-8'));
var names = []; //list of names to prevent dupes
//map of food string to texture(path)
var compositeData = [];
var recipes = [];
var group = 0;
var iter = 0;
compositeData[group] = {};
foods.forEach((ele,idx,arr) => {
    let name = getName(ele);

    let path = "generated/" + generation + "/" + name.split(":")[1] + ".png";
    genImage(ele, path);


    
    compositeData[group][name] = path;
    iter++;
    if (iter == pergen) {
        iter = 0;
        group++;
        compositeData[group] = {};
    }
    genRecipes(ele,name);
});


//obj of previous gen images, path to save new image to
function genImage(obj, path){
    var command = ""
    var first = true; //wheter we are on image 1 or image 2 in smush
    for (let f in obj) { //p is path to one image
        let p = obj[f];

        if (first) {
            command += "magick " + p;
            first = false;
            
        } else {
            command += " " + p + " -background transparent -gravity east " + randSign() + "smush .1 PNG:- | magick PNG:-"
        }
        
    }
    command += " " + path;
    command = command.replaceAll('\n', "");
    //console.log("\n\n Command:" + command);
    proc.execSync(command);
}


function randSign(){
    if (Math.round(Math.random()) == 1){
        return "+";
    } else return "-";
    
}
function genRecipes(obj, name){
    let foods = Object.keys(obj);
    let recipe = {
        amount: 1,
        output: name,
        inputs: foods
    }
    recipes.push(recipe);
}
function getName(obj){
    let name = "kubejs:";

    let foods = Object.keys(obj);

    foods.forEach((ele,idx,arr) =>{
        //add first 3 letters of previous name to next name
        name += ele.split(':')[1].slice(0, 3);
    })
    while (names.find((f) => f==name)){
          
        name += "1"; //prevent duplicate entries
    
    }
    names.push(name);
    return name;

}
fs.writeFileSync("generated/recipe"+ generation + ".json", JSON.stringify(recipes));
//fs.writeFileSync("generated/"+ generation +".json", JSON.stringify(compositeData));