const path = require("path");
const fs = require("fs");

const qjsDir = path.resolve("./qjs");
const importRegex = /import .* from "\..*"/g;

const insert = (line, start, end, content) =>
  [line.slice(0, start), content, line.slice(end)].join("");

// find all js files in qjs folder
const traverse = (dirname) => {
  fs.readdirSync(dirname).forEach((file) => {
    const fp = path.join(dirname, file);
    if (path.extname(fp) === "") traverse(fp);
    if (path.extname(fp) === ".js") {
      // check if has file imports
      const content = fs.readFileSync(fp).toString();
      const found = content.matchAll(importRegex);
      let wasChanged = false;
      const lines =
        found !== null
          ? content.split("\n").map((it) => {
              const line = it.trim();
              if (line.includes("import ") && line.includes('./') && !line.includes('.js')) {
                const fixedLine = insert(
                  line,
                  line.lastIndexOf('"'),
                  line.lastIndexOf('"') + 1,
                  '.js"'
                );
                const split = fixedLine.split('"');
                const importPath = split[split.length - 2];

                const fullImportPath = path.resolve(
                  path.join(dirname, importPath)
                );
                const fileExists = fs.existsSync(fullImportPath);
                const finalFixedLine = fileExists
                  ? fixedLine
                  : insert(line, line.length - 2, line.length - 1, '/index.js"');

                wasChanged = true;
                return finalFixedLine;
              }
              return line;
            })
          : [];

      if (wasChanged) {
        console.log("Editing", fp);
        fs.writeFileSync(fp, lines.join("\n"), { encoding: "utf8", flag: "w" });
      }
    }
  });
};

console.log('\tStarting file traversal')
traverse(qjsDir);

console.log('\tCreating test file');
fs.writeFileSync('./qjs/testy.js', `
import connect from "./index.js";

const run = async () => {
  try {
    print('before connect')
    const usp = await connect({
      host: "iopsys.lan",
      username: "admin",
      password: "admin",
      port: 9001,
      protocol: "ws",
    });

    print('after connect')

    const res = await usp.get("Device.DeviceInfo.");
    print('get result')
    print(JSON.stringify(res, null, 2))

    await usp.disconnect();
    print('after disconnect')
  } catch(err) {
    print("ERROR")
    print(err)
    print(err.stack)
  }
};

run();
print('after run');
`)