'use strict';

var _stringify = require('babel-runtime/core-js/json/stringify');

var _stringify2 = _interopRequireDefault(_stringify);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var exec = require('child_process').exec;

var PROGRAMS = {
  node: {
    getVersion: runVersionCommand.bind(null, 'node --version')
  },
  npm: {
    getVersion: runVersionCommand.bind(null, 'npm --version')
  },
  weex: {
    getVersion: runVersionCommand.bind(null, 'weex --version')
  }
};

function runVersionCommand(command, callback) {
  exec(command, function (execError, stdin, stderr) {
    var commandDescription = (0, _stringify2.default)(command);
    if (execError && execError.code === 127) {
      return callback(null, {
        notfound: true
      });
    } else if (execError || stderr) {
      var runError = new Error('Command failed: ' + commandDescription);
      if (stderr) {
        runError.stderr = stderr.trim();
      }
      if (execError) {
        runError.execError = execError;
      }
      return callback(null, {
        error: runError
      });
    } else {
      var version = stdin.toString().split('\n');
      for (var i = version.length - 1; i >= 0; i--) {
        if (!version[i]) {
          version.splice(i, 1);
        } else {
          version[i] = version[i].trim();
        }
      }
      if (command.indexOf('weex') !== -1) {
        var weexVersion = {};
        var temp = void 0;
        var _version = stdin.toString().split('\n');
        for (var _i = _version.length - 1; _i >= 0; _i--) {
          if (!_version[_i]) {
            _version.splice(_i, 1);
          } else {
            temp = _version[_i].split(':');
            if (temp.length < 2) {
              weexVersion['weex'] = _version[_i].replace(/[\s|v]/g, '');
            } else {
              weexVersion[temp[0].replace(/[\s|-]/g, '')] = temp[1].replace(/[\s|v]/g, '');
            }
          }
        }
        return callback({
          version: weexVersion
        });
      } else {
        return callback({
          version: stdin.toString().split('\n')[0].replace('v', '').trim()
        });
      }
    }
  });
}

exports.getVersionOf = function (name, callback) {
  PROGRAMS[name].getVersion(callback);
};