package leigh.tesseract;

import leigh.mecha.json.JSONObject;

import java.io.IOException;
import java.util.Map;

public class JsonResultWriter extends ResultWriterBase {
    boolean hasEmitted = false;

    public JsonResultWriter() {
        System.out.println("{\"output\":[");
    }

    private void emitIfRequired() {
        if (hasEmitted == false) {
            hasEmitted = true;
        } else {
            System.out.print(",\n");
        }
    }

    @Override
    public void output(String hostname, String result, int returnCode) throws IOException {
        super.output(hostname, result, returnCode);
        synchronized (this) {
            JSONObject obj = new JSONObject();
            obj.put("hostname", hostname);
            obj.put("exitCode", returnCode);
            obj.put("result", result);
            emitIfRequired();
            System.out.print(obj);
        }
    }

    @Override
    public void finish() {
        hasEmitted = false;

        System.out.println("],\"histogram\":[");

        for (Map.Entry<String, Integer> entry : getCounter().getCounts().entrySet()) {
            JSONObject ej = new JSONObject();
            ej.put("result", entry.getKey());
            ej.put("count", entry.getValue());
            emitIfRequired();
            System.out.print(ej);
        }

        System.out.println("]}");
    }
}
