package lc.dnd.cardmaker;

import lc.mecha.json.JSONObject;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.*;
import java.util.Properties;

/**
 * Format a <code>spells.json</code> file into MarkDown for use with various note-taking systems such as
 * Obsidian. The spells file is included in the resources, it does not have to be supplied by the user.
 *
 * @author Alex Leigh
 */
public class SpellNoteMakerCmd {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(SpellNoteMakerCmd.class);

    public static void main(String[] args) throws IOException {
        var is = logger.getClass().getResourceAsStream("/spells.json");
        var spells = new JSONObject(is);

        File output = new File("output");
        //noinspection ResultOfMethodCallIgnored
        output.mkdirs();

        Properties props = new Properties();
        props.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        props.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        var velocityEngine = new VelocityEngine(props);
        velocityEngine.init();
        var t = velocityEngine.getTemplate("/spellcard.vm");
        for (String key : spells.keySet()) {
            JSONObject spell = spells.getJSONObject(key);
            var context = new VelocityContext();

            context.put("name", key);
            for (String objKey : spell.keySet()) {
                context.put(objKey, spell.get(objKey));
            }

            String outputFilename = "output" + File.separator + key + ".md";
            try (OutputStream os = new FileOutputStream(outputFilename)) {
                try (OutputStreamWriter osw = new OutputStreamWriter(os)) {
                    t.merge(context, osw);
                }
            }
        }
    }
}
