package lc.dnd.cardmaker;

import lc.mecha.json.JSONArray;
import lc.mecha.json.JSONObject;
import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;
import lc.mecha.util.StringAccumulatorV2;
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;

/**
 * Generate markdown formatted note cards for each Item in the <code>items.json</code> database.
 *
 * @author Alex Leigh
 */
public class FifthEdItemNoteMakerCmd {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(FifthEdItemNoteMakerCmd.class);

    public static void main(String[] args) throws IOException {
        makeCards("/items.json");
    }

    public static void makeCards(String filename) throws IOException {
        var is = logger.getClass().getResourceAsStream(filename);
        var doc = 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("/5e_item.vm");

        var items = doc.getJSONArray("item");
        for (int i = 0; i < items.length(); i++) {
            JSONObject item = items.getJSONObject(i);
            var context = new VelocityContext();

            for (String objKey : item.keySet()) {
                context.put(objKey, item.get(objKey));
            }

            var entries = item.optJSONArray("entries");
            if (entries != null)
                context.put("description", toStringEntry(entries));

            String safeName = item.getString("name").replace("/", "_");
            String outputFilename = "output" + File.separator + safeName + ".md";
            try (OutputStream os = new FileOutputStream(outputFilename)) {
                try (OutputStreamWriter osw = new OutputStreamWriter(os)) {
                    t.merge(context, osw);
                }
            }
        }
    }

    public static String toStringEntry(JSONArray arr) {
        var sa = new StringAccumulatorV2("\n\n");
        for (int idx = 0; idx < arr.length(); idx++) {
            if (arr.isString(idx))
                sa.add(arr.getString(idx));
        }
        return sa.asString();
    }
}
