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

function getScriptsPkg() {
  const rootPath = __dirname.split('node_modules')[0];
  return require(path.join(rootPath, '/node_modules/@enplug/scripts/package.json'));  
}

function verifyNodeVersion(pkg) {
  const scriptsPkg = getScriptsPkg();
  const allowedNodeVersion = scriptsPkg.config.allowedNodeVersion;
  
  return new Promise((resolve, reject) => {
    let nodeVersionOk = false;

    // Verify Node version
    const nodeVersion = process.version;
    if (nodeVersion.startsWith(`v${allowedNodeVersion}`)) {
      nodeVersionOk = true;
    }

    // Verify that installed @enplug/scripts version matches the latest available scripts version.
    const { exec } = require('child_process');
    const installedScriptsVersion = pkg.devDependencies['@enplug/scripts'] || pkg.dependencies['@enplug/scripts'];
    if (!installedScriptsVersion) {
      return reject(`Please install @enplug/scripts as a devDepenency`);
    }

    exec('npm show @enplug/scripts version', (err, latestScriptsVersion, stderr) => {
      if (!latestScriptsVersion || stderr) {
        return reject(stderr);
      }
      latestScriptsVersion = latestScriptsVersion.replace(/\n/g, '');

      const scriptsVersionOk = [latestScriptsVersion, 'rc', 'alpha', 'beta', 'dev'].reduce(
        (result, v) => result || installedScriptsVersion.indexOf(v) >= 0,
        false
      );

      console.log(`Installed ${chalk.default.green('@enplug/scripts')} version: ${chalk.default[scriptsVersionOk ? 'greenBright' : 'redBright'](installedScriptsVersion)}`);
      console.log(`Latest ${chalk.default.green('@enplug/scripts')} version: ${chalk.default.greenBright(latestScriptsVersion)}\n`);

      if (nodeVersionOk && scriptsVersionOk) {
        resolve();
      } else if (!nodeVersionOk) {
        reject(`Unable to run build script. Install ${chalk.default.green('NodeJS')} ${chalk.default.cyan(`v${allowedNodeVersion}.x.x`)} instead of ${chalk.default.cyan(nodeVersion)}`);
      } else if (!scriptsVersionOk) {
        const msg = `Unable to run build. Version ${chalk.default.cyan(latestScriptsVersion)} of ${chalk.default.green('@enplug/scripts')} should be installed.`
          + `\nRun ${chalk.default.green('npm install -D @enplug/scripts@latest')}\n\n`;
        reject(msg);
      }
    });
  });
}

module.exports = verifyNodeVersion;
