const path = require('path');
const chalk = require('chalk');
const shell = require('shelljs');
const checkScriptsUpToDate = require('./checkScriptsUpToDate');
const extractResourcesAndReplaceUrls = require('./extractResourcesAndReplaceUrls');
const initOfflineConfig = require('./initOfflineConfig');
const rootPath = __dirname.split('node_modules')[0];

function buildAngular(pkg, options, destination, version) {
  return checkScriptsUpToDate(pkg).then(
    () => runBuild(pkg, options, destination, version).then(() => {
      if (!options.nooffline && !options.electron) {
        return copyOfflineSupportWorker(pkg, options, rootPath);
      }
    }),
    err => {
      throw new Error(err);
    }
  );
}

function runBuild(pkg, options, destination, version) {
  const angularVersion = getAngularVersion(pkg);

  return new Promise(resolve => {
    let baseHref = path.posix.join('/', destination, version, '/');
    if (options.ignoreversion) {
      baseHref = path.posix.join('/', destination, '/');
    } if (options.electron) {
      baseHref = './';
    }
    let command = 'ng build --base-href ' + baseHref;

    if (angularVersion < 6 && options.prod) {
      console.log(`Angular version < 6. Adding --env=prod`);
      command += ' --prod';
      command += ' --env=prod'; // set env to prod
    } else if (angularVersion >= 6) {
      console.log(`Angular version >= 6.`);
      if (options.configuration) {
        command += ' --configuration=' + options.configuration;
      }
    }

    console.log(`Running command: ${chalk.default.yellowBright(command)}`);
    shell.exec(command, () => resolve());
  });
}

function getAngularVersion(pkg) {
  let angularVersion = pkg['dependencies']['@angular/core'] || pkg['devDependencies']['@angular/core'];
  angularVersion = angularVersion.replace(/[^\d.-]/g, '');
  angularVersion = parseFloat(angularVersion);
  return angularVersion;
}

/**
 * Copies offline support service woker over to the application.
 */
function copyOfflineSupportWorker(pkg, options, rootPath) {
  return new Promise((resolve) => {
    try {
      const commonStaticResources = [
        './',
        './index.html',
        './enplug-offline-worker.js'
      ];

      let indexFilePath = path.join(rootPath, 'dist/index.html');

      let configPath = path.join(rootPath, 'offline.config.json');
      let srcFilePath = path.join(__dirname, '../templates/enplug-offline-worker.js');
      let destFilePathDist = path.join(rootPath, 'dist/enplug-offline-worker.js');
      let destFilePathSrc = path.join(rootPath, 'src/enplug-offline-worker.js');
      if (options.webplayer) {
        srcFilePath = path.join(__dirname, '../templates/enplug-player-offline-worker.js');
      }

      let offlineConfig = initOfflineConfig(require(configPath), pkg, commonStaticResources);

      extractResourcesAndReplaceUrls(offlineConfig, pkg, indexFilePath, srcFilePath, [destFilePathDist, destFilePathSrc])
        .then(resolve);
    } catch (e) {
      console.warn(`Unable to copy offline support service worker. Please check whether ${chalk.default.cyan('offline.config.json')} exists.`);
      resolve();
    }
  });
}

module.exports = buildAngular;
