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

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

const {
  testSuluDir,
  testPluginsDirsList,
  testPluginsDirsString,
  testWriteResultDir,
  mockPluginManifest,
} = macros();

describe("src/libs/stage1/parseArgs.spec.js", () => {
  beforeEach(() => {
    beforeEachTest();
  });
  afterEach(() => {
    afterEachTest();
  });
  describe("parseArgs()", () => {
    it("should validate correct input, no plugins passed, parse flags", () => {
      const { suluDir, buildOutputPath, manifests, options } = parseArgs({
        writeDir: testWriteResultDir,
        suluDir: testSuluDir,
        pluginPaths: "",
        _v: true,
        _o: true,
        _s: true,
        _t: true,
        _p: true,
      });

      assert.deepStrictEqual(suluDir, testSuluDir, "correct sulu dir built");
      assert.deepStrictEqual(
        buildOutputPath,
        testWriteResultDir,
        "correct build dir built"
      );
      assert.deepStrictEqual(manifests, [], "correct empty manifest list");
      assert.deepStrictEqual(options, {
        reloadOnChanges: true,
        incrementalBuild: true,
      });
    });
    it("should validate plugins (correct manifests)", () => {
      const { manifests } = parseArgs({
        suluDir: testSuluDir,
        writeDir: testWriteResultDir,
        pluginPaths: testPluginsDirsString,
      });

      assert.deepStrictEqual(
        manifests,
        testPluginsDirsList.map((p) => ({
          absolutePath: p,
          manifest: mockPluginManifest,
        })),
        "correct empty manifest list"
      );
    });
    it("should throw if incorrect manifest", () => {
      fs.writeFileSync(
        path.join(testPluginsDirsList[0], "suluPluginManifest.json"),
        `{
        "excludePattern": "^$",
        "integrate_package_file_dependencies": true,
        "integrate_package_file_dev_dependencies": true
      }`
      );

      assert.throws(() => {
        parseArgs({
          suluDir: testSuluDir,
          writeDir: testWriteResultDir,
          pluginPaths: testPluginsDirsString,
        });
      }, "pattern field missing");
    });
    it("should throw if write folder exists while w flag is set, and not when isnt", () => {
      fs.createFileSync(path.join(testWriteResultDir, "index.js"));
      assert.throws(() => {
        parseArgs({
          suluDir: testSuluDir,
          writeDir: testWriteResultDir,
          pluginPaths: "",
          _w: true,
          _v: true,
        });
      });
      assert.doesNotThrow(() => {
        parseArgs({
          suluDir: testSuluDir,
          writeDir: testWriteResultDir,
          pluginPaths: "",
          _v: true,
        });
      });
    });
  });
});
