'use strict';

const path = require('path');
const execa = require('execa');

const tools = require('../tools');
const configUtils = require('../../csdr/config/config-utils');


module.exports.run = () => {

  const prj = configUtils.projects.getProject();

  if (!prj || !prj.name) {
    tools.logWarning(`ERROR : unable to lookup the project : ${tools.getArgs().root}`);
    tools.logInfo('It should belong to the local project list installed : ');
    configUtils.projects.getProjects().map(p => console.log(p.name));
    tools.logInfo('\n\n');
    process.exit(1);
  }

  const a11y = path.resolve(process.cwd(), 'node_modules', 'pa11y-ci', 'bin', 'pa11y-ci');

  return Promise.resolve()
    .then(() => {
      tools.logTitle(`Running a11y report for : ${prj.name}...`);
      console.log(prj);

      if (!tools.isFileExists(`${prj.paths.angularPath}\\a11y-config.json`)) {
        tools.logError(`Missing configuration file : a11y-config.json in ${prj.paths.angularPath}`);
        throw new 'FILE_NOT_FOUND';
      }      
    })

    // trigger a11y on project
    .then(() => {
      let args;

      args = ['--max_old_space_size=8192', a11y, '--config=a11y-config.json'];

      tools.logInfo(`a11y runs with args ${args}`);

      return execa('node', args, { cwd: prj.paths.angularPath, stdio: 'inherit' });
    })
    .catch((e) => {
      throw e;
    });
}
