package org.bdware.sc.contractGen;

import org.apache.velocity.Template;
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 org.bdware.sc.util.JsonUtil;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class ContractGenerator {
    static VelocityEngine ve = init();

    public static String generateAPIContract(Map<String, String> arg) {
        VelocityContext ctx = new VelocityContext();
        Template script = ve.getTemplate("org/bdware/sc/sc/contractGen/timeindexcontract.vm");
        ctx.put("indexData", arg.get("indexData"));
        ctx.put("datalen", arg.get("datalen"));
        ctx.put("sdkpath", arg.get("sdkpath"));
        ctx.put("syncbyheight", arg.get("syncbyheight"));
        StringWriter writer = new StringWriter();
        script.merge(ctx, writer);
        return writer.toString();
    }

    public static String generateIndexContract(long availableDate, String url, String method, Map<String, String> header,
                                               Map<String, String> arg) {
        VelocityContext ctx = new VelocityContext();

        Template script = ve.getTemplate("com/yancloud/sc/indexcontract.vm");
        String onblock = "var hash = com.yancloud.sc.util.HashUtil.str16ToBytes(args);\n print(hash)";
        ctx.put("onBlock", onblock);
        StringWriter writer = new StringWriter();
        script.merge(ctx, writer);
        return writer.toString();
    }

    private static VelocityEngine init() {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        return ve;
    }

    public static String generateFTPContract(long availableDate) {
        VelocityContext ctx = new VelocityContext();
        Template script = ve.getTemplate("org/bdware/sc/sc/ftpcontract.vm");
        String[][] initList = {{"availableDate", availableDate + ""}};
        ctx.put("initList", initList);
        ctx.put("validate", "YancloudUtil.currentTimeMillis()>Global.availableDate");
        StringWriter writer = new StringWriter();
        script.merge(ctx, writer);
        return writer.toString();
    }

    private static String stringify(String url) {
        return JsonUtil.toJson(url);
    }

    private static String convertMap(Map<String, String> arg) {
        if (null == arg)
            arg = new HashMap<>();
        return JsonUtil.toJson(arg);
    }
}
