#include "vm.hpp"
#include <string>

using namespace sliger;

void FlameGraphBuilder::to_json(json::Writer& writer) const
{
    fg_node_to_json(writer, 0);
}

void FlameGraphBuilder::fg_node_to_json(
    json::Writer& writer, size_t node_index) const
{
    const auto& node = this->nodes[node_index];
    writer << "{\"fn\":" << std::to_string(node.fn)
           << ",\"acc\":" << std::to_string(node.acc)
           << ",\"parent\":" << std::to_string(node.parent)
           << ",\"children\":[";
    auto first = true;
    for (auto child_index : node.children) {
        if (!first) {
            writer << ",";
        }
        first = false;
        fg_node_to_json(writer, child_index);
    }
    writer << "]}";
}

void CodeCoverageBuilder::to_json(json::Writer& writer) const
{
    writer << "[";
    writer.add_comma_seperated(
        this->entries, [&](json::Writer& writer, CCPosEntry entry) {
            writer << "{\"index\":" << std::to_string(entry.pos.index)
                   << ",\"line\":" << std::to_string(entry.pos.line)
                   << ",\"col\":" << std::to_string(entry.pos.col)
                   << ",\"covers\":" << std::to_string(entry.covers) << "}";
        });
    writer << "]";
}
