const { describe, it, beforeEach, afterEach } = require("mocha");
const assert = require("assert");
const { replaceImports } = require("./replaceImports");
const fs = require("fs-extra");
const path = require("path");

const {
  macros,
  beforeEachTest,
  afterEachTest,
} = require("../../resources/tests");

const { testSuluDir } = macros();

describe("src/libs/stage1/transferPlugins.spec.js", () => {
  beforeEach(() => {
    beforeEachTest();
  });

  afterEach(() => {
    afterEachTest();
  });

  describe("replaceImports()", () => {
    it("should match and replace correct sulu-base imports", () => {
      const replaceTestFile = path.join(testSuluDir, "test-replace.js");

      const inserts = [
        "= require(\"sulu-base/@a\")",
        "=require(\"sulu-base/@a\")",
        "=require(\"sulu-base/@a/b\")",
        "= require('sulu-base/@a')",
        " from \"sulu-base/@a\"",
        " from \"sulu-base/@a/b\"",
      ];

      inserts.forEach((i) => {
        fs.appendFileSync(replaceTestFile, `${i}\n`);
      });

      replaceImports({ src: replaceTestFile });

      const results = fs
        .readFileSync(replaceTestFile)
        .toString()
        .split("\n")
        .filter((x) => x);

      const expected = [
        "= require(\"/@a\")",
        "=require(\"/@a\")",
        "=require(\"/@a/b\")",
        "= require('/@a')",
        " from \"/@a\"",
        " from \"/@a/b\"",
      ];

      for (let i in results) {
        assert.deepEqual(
          results[i],
          expected[i],
          `It should replace \n${inserts[i]}\nwith \n${expected[i]}`
        );
      }
    });

    it("should not match and not replace incorrect sulu-base imports", () => {
      const replaceTestFile = path.join(testSuluDir, "test-replace.js");

      const inserts = [
        "= require(\"asulu-base\")",
        "=require(\"sulu-basea\")",
        "=require(\"a/sulu-base\")",
        "= require('sulu-basea')",
        "from (\"-sulu-base\")",
        "from (\"sulu-base-\")",
      ];

      inserts.forEach((i) => {
        fs.appendFileSync(replaceTestFile, `${i}\n`);
      });

      replaceImports({ src: replaceTestFile });

      const results = fs
        .readFileSync(replaceTestFile)
        .toString()
        .split("\n")
        .filter((x) => x);

      const expected = [
        "= require(\"asulu-base\")",
        "=require(\"sulu-basea\")",
        "=require(\"a/sulu-base\")",
        "= require('sulu-basea')",
        "from (\"-sulu-base\")",
        "from (\"sulu-base-\")",
      ];

      for (let i in results) {
        assert.equal(
          results[i],
          expected[i],
          `It should leave \n${inserts[i]} without change`
        );
      }
    });
  });
});
