package org.bdware.sc.debugger;

import com.google.gson.JsonObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.bdware.sc.ContractProcess;
import org.bdware.sc.bean.Contract;
import org.bdware.sc.bean.ContractExecType;
import org.bdware.sc.conn.ResultCallback;
import org.bdware.sc.get.GetMessage;
import org.bdware.sc.http.HttpUtil;
import org.bdware.sc.util.FileUtil;
import org.bdware.sc.util.JsonUtil;

import java.util.Map;

public class DebugMain {
    static Logger LOGGER = LogManager.getLogger(DebugMain.class);

    public static void main(String[] args) {
        String content = FileUtil.getFileContent("./debugconf.json");
        DebugConfig config = JsonUtil.fromJson(content, DebugConfig.class);
        inject(config);
        ContractProcess.main(new String[]{"-port=" + config.port, "-cmi=" + config.cmi, "-disablePID"});
        ResultCallback printCallback
                = new ResultCallback() {
            @Override
            public void onResult(String str) {
                LOGGER.info(str);
            }
        };
        ContractProcess.instance.handler.setDBInfo(wrap("", config.dbPath), printCallback);
        ContractProcess.instance.handler.registerMangerPort(wrap("", Integer.valueOf(config.cPort)), printCallback);
        ContractProcess.instance.handler.setContractBundle(wrap("", config.contract), printCallback);
        String urlFormat = ("http://%s/SCIDE/SCManager?action=reconnectAll&owner=%s");

        String url = String.format(urlFormat, config.agentHttpAddr, config.pubKey);
        Map<String, Object> resp = HttpUtil.httpGet(url);
        String data = (String) resp.get("response");
        LOGGER.info(JsonUtil.toPrettyJson(JsonUtil.parseStringAsJsonObject(data)));
        LOGGER.info("start done!");
    }

    private static void inject(DebugConfig config) {
        String urlFormat = ("http://%s/SCIDE/SCManager?action=%s&arg=%s");
        String url = String.format(urlFormat, config.agentHttpAddr, "getAgentConfig", "");
        Map<String, Object> resp = HttpUtil.httpGet(url);
        String data = (String
                ) resp.get("response");
        JsonObject jsonObject = JsonUtil.parseStringAsJsonObject(data);
        config.cmi = jsonObject.get("cmi").getAsString();
        config.dbPath = jsonObject.get("dbPath").getAsString();
        config.cPort = jsonObject.get("cPort").getAsInt();
        config.port = jsonObject.get("port").getAsInt();
        JsonObject ownerAndScript = new JsonObject();
        String arg = "abc&owner=" + config.pubKey + "&script=" + config.script;
        url = String.format(urlFormat, config.agentHttpAddr, "allocateKeyPair", arg);
        resp = HttpUtil.httpGet(url);
        LOGGER.info(url);
        String contractStr = (String) resp.get("response");
        LOGGER.info("[ContratStr] " + contractStr);
        Contract contract = JsonUtil.fromJson(contractStr, Contract.class);
        config.contract = contract;
        contract.setType(ContractExecType.Sole);
    }

    private static GetMessage wrap(String operation, Object arg) {
        return wrap(operation, JsonUtil.toJson(arg));
    }

    private static GetMessage wrap(String operation, String arg) {
        GetMessage msg = new GetMessage();
        msg.method = operation;
        msg.arg = arg;
        return msg;
    }

    static class DebugConfig {
        String script;
        String agentHttpAddr;
        String pubKey;
        String privKey;
        //AutoAppend

        int port;
        String cmi;
        String dbPath;
        int cPort;
        Contract contract;
    }
}
