const path = require('path');
const childProcess = require('child_process');
const execSync = childProcess.execSync;

const utils = require('../utils');
const common = require('./common'); 

module.exports.run = () => {
  let {
    skipLint,
    skipTest,
    skipCompile,
    configuration,
    baseHref,
    servePath,
    watch,
    dryRun,
    maxSpaceSize,
    statsJson,
    ci,
    deployUrl,
    sourceMap,
    configEnvTarget,
    project,
  } = utils.getArgs();

  let prjName = 'app';

  if (project) {
    prjName = project;
  }

  utils.logTitle(`Building application : ${prjName}...`);

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

  return Promise.resolve()
    .then(() => {
      if (configEnvTarget) {
        return common.injectAppConfig();
      }
    })

    .then(() => {
      if (!skipLint) {
          utils.logInfo(`running ng lint ${prjName}`);
          execSync(`ng lint ${prjName}`, { cwd: process.cwd(), stdio: 'inherit' });        
      }
    })

    .then(() => {
      if (!skipLint) {
        utils.logSuccess();
      }
      if (!skipTest) {
        utils.logInfo(`Launching application unit testing...`);

        let args;

        if (maxSpaceSize) {
          args = ['--max_old_space_size=8096', ng, 'test', prjName];
        } else {
          args = [ng, 'test', prjName];
        }

        if (watch) {
          args.push(`--watch=true`);
        } else {
          args.push(`--watch=false`);
        }

        utils.logInfo(`ng test : watching = ${watch || false}`);

        utils.logInfo(`running Angular TEST with args: ${args} on :`);

        if (!dryRun) {
          execSync(`node ${args.join(' ')}`, { cwd: process.cwd(), stdio: 'inherit' });
        }
      }
    })

    .then(() => {
      if (!skipTest) {
        utils.logSuccess();
      }
      utils.logInfo(`Launching application build...`);

      let args;

      if (maxSpaceSize) {
        args = ['--max_old_space_size=8096', ng, 'build', prjName, '--aot'];
      } else {
        args = [ng, 'build', prjName, '--aot'];
      }

      if (statsJson) {
        args.push('--stats-json');
      }

      if (configuration) {
        args.push(`--configuration=${configuration}`);
      } 

      if (baseHref) {
        args.push(`--base-href=${baseHref}`);
      }

      if (servePath) {
        args.push(`--serve-path=${servePath}`);
      }

      if (deployUrl) {
        args.push(`--deploy-url=${deployUrl}`);
      }

      if (ci) {
        args.push('--progress=false');
      }

      if (sourceMap) {
        args.push('--source-map');
      }

      utils.logInfo(`ng build for configuration : ${configuration || 'production'}`);

      utils.logInfo(`running Angular BUILD with args: ${args}`);

      if (!dryRun && !skipCompile) {
        execSync(`node ${args.join(' ')}`, { cwd: process.cwd(), stdio: 'inherit' });
      }
    })

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

