/* libxmq - Copyright (C) 2026 Fredrik Öhrström (spdx: MIT) */

// Parse car.xmq and read strings, integers and doubles from it.

import * as fs from "node:fs";
import { DOMImplementation } from "@xmldom/xmldom";
import type { Document } from "@xmldom/xmldom";
import { parse, XMQParseError } from "libxmq";

/** The text of the element below the root with this name, null if it is missing. */
function getString(doc: Document, name: string): string | null
{
    // The library has no xpath; the DOM finds the elements by name.
    const found = doc.documentElement!.getElementsByTagName(name);
    return found.length > 0 ? found[0].textContent : null;
}

const file = process.argv.length > 2 ? process.argv[2] : "car.xmq";

let doc: Document;
try
{
    // The implicit root car, like xmq --root=car: a config file may also be written
    // without car { }, as several elements at the top.
    doc = parse(fs.readFileSync(file, "utf8"), { dom: new DOMImplementation(), source: file, root: "car" });
}
catch (e)
{
    if (!(e instanceof XMQParseError)) throw e;
    process.stdout.write("Parse error in " + file + "\n" + e.message + "\n");
    process.exit(1);
}

const model = getString(doc, "model");
const num_wheels = parseInt(getString(doc, "num_wheels") ?? "", 10);
const weight = parseFloat(getString(doc, "weight") ?? "");
const history = getString(doc, "history");
// A missing value is null.
const color = getString(doc, "color");

console.log("model      = " + model);
console.log("num_wheels = " + num_wheels);
console.log("weight     = " + weight.toFixed(3));
console.log("color      = " + (color ?? "(not set)"));
console.log("history    =\n" + history);