const { program } = require('commander');
const { generateSuitMap } = require('../lib/gen-suits/generateSuitMap');
const { SourceFile, TargetFile } = require('../lib/gen-suits/file');
const { createServer } = require('../lib/servers/gen-suit-server');
const open = require('open');
const fs = require('fs');
const path = require('path');
const getPort = require('get-port');

program
  .description('An interactive application to parse html test suits which from WPT project and auto generate test specs for Webf.')
  .requiredOption('-s, --source <source_dir>', 'the wpt source file come from')
  .requiredOption('-t, --target <target_dir>', 'where\'s the generated test suit going to');
program.parse(process.argv);

let source = program.source;
let target = program.target;

if (!path.isAbsolute(source)) {
  source = path.join(process.cwd(), source);
}

if (!path.isAbsolute(target)) {
  target = path.join(process.cwd(), target);
}

let sourceFiles = fs.readdirSync(source);
let targetFiles = fs.readdirSync(target);


function getTestSourceFile(files) {
  return files
    .map(name => new SourceFile(name, path.join(source, name)))
    .filter(file => {
      return !file.isDirectory() && file.isTestFile();
    });
}

function getTestTargetFile(files) {
  return files.map(name => new TargetFile(name, path.join(source, name)));
}

(async () => {
  const PORT = await getPort({port: 3300});
  let sourceTestFiles = getTestSourceFile(sourceFiles);
  let targetTestFiles = getTestTargetFile(targetFiles);

  let suits = generateSuitMap(sourceTestFiles, targetTestFiles);
  const server = createServer(suits, source, target, PORT);

  open(`http://127.0.0.1:${PORT}/gen-suit`);
})();

