'use strict';

var RSVP = require('rsvp');
var Promise = RSVP.Promise;
var chalk = require('chalk');
var ui = require('../ui');
var fs = require('fs');
var readFile = RSVP.denodeify(fs.readFile);
var merge = require('lodash-node/modern/objects/merge');

module.exports = function bowerInstall() {
  var bower = require('bower'),
      inquirer = require('inquirer');

  if (!fs.existsSync('.bowerrc')) {
    return 0;
  }

  return readFile('.bowerrc').then(function(bowerConfig) {
    return new Promise(function(resolve, reject) {
      bower.commands.
        install(undefined, { save: true }, merge(bowerConfig, { interactive: true })).
          on('log', function(message) {
            if (message.level === 'conflict') {
              ui.write('  ' + chalk.red('conflict') + ' ' + message.message + '\n');
              message.data.picks.forEach(function(pick, index) {
                ui.write('    ' + chalk.green((index + 1) + ')') + ' ' + message.data.name + ' ' + pick.endpoint.target + '\n');
              });
            } else {
              if (message.level === 'info') {
                ui.write('  ' + chalk.green(message.id) + ' ' + message.message + '\n');
              }
            }
          }).
          on('error', reject).
          on('end', resolve).
          on('prompt', function (prompts, callback) {
              inquirer.prompt(prompts, callback);
            });
    });
  });
};

'use strict';

var RSVP = require('rsvp');
var Promise = RSVP.Promise;
var chalk = require('chalk');
var ui = require('../ui');
var merge = require('lodash-node/modern/objects/merge');
var inquirer = require('inquirer');
var fs = {
  readFile: RSVP.denodeify(require('fs').readFile)
};

module.exports = function bowerInstall() {
  var bower = require('bower');

  return fs.readFile('.bowerrc')
    .then(function(bowerConfig) {
      merge(bowerConfig, { interactive: true });

      return new Promise(function(resolve, reject) {
        bower.commands.install([], { save: true }, bowerConfig) // Packages, options, config
          .on('log', log)
          .on('prompt', inquirer.prompt)
          .on('error', reject)
          .on('end', resolve);
      });
    });
};

function log(message) {
  if (message.level === 'conflict') {
    // e.g.
    //   conflict Unable to find suitable version for ember-data
    //     1) ember-data 1.0.0-beta.6
    //     2) ember-data ~1.0.0-beta.7
    ui.write('  ' + chalk.red('conflict') + ' ' + message.message + '\n');
    message.data.picks.forEach(function(pick, index) {
      ui.write('    ' + chalk.green((index + 1) + ')') + ' ' +
               message.data.name + ' ' + pick.endpoint.target + '\n');
    });

  } else if (message.level === 'info') {
    // e.g.
    //   cached git://example.com/some-package.git#1.0.0
    ui.write('  ' + chalk.green(message.id) + ' ' + message.message + '\n');
  }
}
Refactor bower-install.js