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

function checkScriptsUpToDate(pkg) {
  return new Promise((resolve, reject) => {
    // 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 (scriptsVersionOk) {
        resolve();
      } else {
        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 = checkScriptsUpToDate;
