'use strict';

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

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

// FETCH ARGS
const { watch, skipCoverage, timeout, build } = tools.getArgs();



module.exports.run = () => {
  let pkg, sub;

  return Promise.resolve()
    .then(() => {
      pkg = configUtils.packages.getPackage();
    })
    .then(() => {
      return new Promise((resolve, reject) => {
        const { subEntry } = tools.getArgs();
        sub = subEntry;
        if(subEntry) {
          tools.getFilesGlob(`${pkg.paths.fromRoot}/${subEntry}`, `**/package.json`)
            .then((files) => {
              if (files.length === 0) {
                tools.logWarning(`no sub-entries found within package ${pkg.name}`);
                return;

              } else {
                let subEntryPath = files.filter((f) => {
                  return f.indexOf(subEntry) > -1;
                })[0];

                if (!subEntryPath) {
                  tools.logWarning(`${subEntry} can't be found in sub-folders of package (must contains package.json file for sub-entry definition)`);
                  tools.logWarning(`Try to run : yarn run pkg:build eui-components --sub-entry ${subEntry}`);
                  throw new Error('sub-entry not found');
                  return;

                } else {
                  subEntryPath = subEntryPath.replace('/ng-package.json', '');
                  tools.logInfo(`${subEntryPath} found... injecting angular.json for sub entry`);

                  return configUtils.angular.registerAngularPackageSubEntry(subEntry, subEntryPath, pkg);
                }
                ;
              }
            })
            .then(() => resolve())
            .catch((e) => reject(e));
        } else {
          resolve();
        }
      });
    })
    .then(() => {
      tools.logInfo(`Testing package : ${pkg.name}...`);

      const ng = path.resolve(process.cwd(), 'node_modules', '@angular', 'cli', 'bin', 'ng');

      let args = ['--max_old_space_size=8096', ng, 'test', sub ? sub : pkg.name];

      args.push('--code-coverage');

      tools.logInfo(`running ng test : with args: ${args} on folder : ${pkg.paths.root}`);

      return execa('node', args, { cwd: pkg.paths.root, stdio: 'inherit' });
    })

    .catch((e) => {
      throw e;
    })
}



module.exports.runMocha = (pkg) => {
  return Promise.resolve()
    .then(() => {
      tools.logTitle(`Executing Mocha test for pkg: ${pkg.name}`);

      // set jest binary
      const mocha = path.resolve(process.cwd(), 'node_modules', 'mocha', 'bin', '_mocha');
      const nyc = path.resolve(process.cwd(), 'node_modules', 'nyc', 'bin', 'nyc');

      // default arguments
      let args;

      if (!skipCoverage && !build) {
        args = [nyc, '--reporter=text', mocha, pkg.paths.fromRoot +  '/**/*.test.js'];
      } else {
        args = [mocha, pkg.paths.fromRoot +  '/**/*.test.js'];
      }
      if (watch) {
        args.push('--watch');
      }
      if (timeout) {
        args.push(`--timeout ${timeout}`);
      } else {
        args.push('--timeout 20000');
      }

      return execa('node', args, { cwd: process.cwd(), stdio: 'inherit' });
    })

    .catch((e) => {
      throw e;
    })
}



