package org.bdware.sc;

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(long availableDate, String url, String method, Map<String, String> header,
                                             Map<String, String> arg) {
        VelocityContext ctx = new VelocityContext();

        Template script = ve.getTemplate("org/bdware/sc/sc/datacontract.vm");
        String[][] initList = {{"availableDate", availableDate + ""}, {"baseUrl", stringify(url)},
                {"method", stringify(method)}, {"headers", convertMap(header)}, {"arg", convertMap(arg)}};
        ctx.put("initList", initList);
        ctx.put("validate", "YancloudUtil.currentTimeMillis()>Global.availableDate");
        ctx.put("validateFailedMsg", "\"key expired\"");
        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 (arg == null) {
            arg = new HashMap<>();
        }
        return JsonUtil.toJson(arg);
    }
}
