// TODO v21 - app prebuild for config injection from eUI tools

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 { configuration, baseHref, servePath, host, proxyConfig, maxSpaceSize, port, disableHostCheck, open, debug, configEnvTarget, noLiveReload } = utils.getArgs();

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

  const prjName = 'app';

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

    // trigger ng serve with parameters provided
    .then(() => {
      utils.logTitle(`Serving application : ${prjName}...`);

      let args;

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

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

      if (proxyConfig) {
        args.push(`--proxy-config=${proxyConfig}`);
      }

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

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

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

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

      if (disableHostCheck) {
        args.push(`--disable-host-check`);
      }

      if (!(open === 'false')) {
        args.push('--open=true');
      }

      if (noLiveReload) {
        args.push('--live-reload=false');
      }

      utils.logInfo(`ng serve with args ${args}`);

      return execSync(`node ${args.join(' ')}`, { cwd: process.cwd(), stdio: 'inherit' });
    })
    .catch((e) => {
      throw e;
    });
}
