import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import assert from "node:assert/strict";

import { createLinuxCncIniSdk } from "../../../runtime/sdk/src/index.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = resolve(__dirname, "../../..");
const wasmPath = resolve(rootDir, "runtime/ui/ini-panel/linuxcnc_ini.wasm");

const ini = await createLinuxCncIniSdk({
  wasmBinary: readFileSync(wasmPath),
  print() {},
  printErr(message) {
    console.error(message);
  },
});

ini.writeTextFile(
  "/work/node-smoke.ini",
  `[EMC]
MACHINE = wasm-node-smoke

[TRAJ]
LINEAR_UNITS = mm
COORDINATES = X Y Z A B

[KINS]
KINEMATICS = xyzbc-trt-kins
JOINTS = 5

[RS274NGC]
PARAMETER_FILE = node-linuxcnc.var

[EMCIO]
RANDOM_TOOLCHANGER = ON
NON_RANDOM_TOOLCHANGER = no
TOOL_TABLE = node-tool.tbl
`,
);

assert.equal(
  ini.getString("/work/node-smoke.ini", "EMC", "MACHINE"),
  "wasm-node-smoke",
);
assert.equal(ini.getString("/work/node-smoke.ini", "TRAJ", "LINEAR_UNITS"), "mm");
assert.equal(
  ini.getString("/work/node-smoke.ini", "KINS", "KINEMATICS"),
  "xyzbc-trt-kins",
);
assert.equal(
  ini.getString("/work/node-smoke.ini", "RS274NGC", "PARAMETER_FILE"),
  "node-linuxcnc.var",
);
assert.equal(
  ini.getString("/work/node-smoke.ini", "EMCIO", "TOOL_TABLE"),
  "node-tool.tbl",
);
assert.equal(ini.getString("/work/node-smoke.ini", "TRAJ", "MISSING"), null);
assert.equal(ini.getBool("/work/node-smoke.ini", "EMCIO", "RANDOM_TOOLCHANGER"), true);
assert.equal(ini.getBool("/work/node-smoke.ini", "EMCIO", "NON_RANDOM_TOOLCHANGER"), false);
assert.equal(ini.getBool("/work/node-smoke.ini", "EMCIO", "MISSING"), null);

assert.deepEqual(ini.getFields("/work/node-smoke.ini", {
  machine: { section: "EMC", tag: "MACHINE" },
  joints: { section: "KINS", tag: "JOINTS" },
  parameterFile: { section: "RS274NGC", tag: "PARAMETER_FILE" },
  toolTable: { section: "EMCIO", tag: "TOOL_TABLE" },
}), {
  machine: "wasm-node-smoke",
  joints: "5",
  parameterFile: "node-linuxcnc.var",
  toolTable: "node-tool.tbl",
});

console.log("ini_wasm_node_smoke=ok");
