'use strict';

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

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


module.exports.serve = () => {

  let { configuration, baseHref, servePath, host, proxyConfig, maxSpaceSize, port, disableHostCheck, open, debug, configEnvTarget, noLiveReload } = tools.getArgs();

  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 ng = path.resolve(process.cwd(), 'node_modules', '@angular', 'cli', 'bin', 'ng');


  return Promise.resolve()
    .then(() => {
      tools.logTitle(`Serving application : ${prj.name}...`);

      if (debug) {
        console.log(prj);
      }
    })

    .then(() => {
      return preBuildUtils.projects.preBuild(prj, configuration, false, configEnvTarget);
    })


    // trigger ng serve with parameters provided
    .then(() => {
      let args;

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

      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');
      }

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

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