var inquirer = require('inquirer'),
    Q = require('q');

var prompts = {};

module.exports = prompts;

// Search for fonts
prompts.search = function() {
  var deferred = Q.defer();

  inquirer.prompt([{
    type: 'input',
    name: 'query',
    message: 'Search for fonts'
  }], function(input) {
    deferred.resolve(input.query);
  });

  return deferred.promise;
};

// Select required fonts
prompts.fonts = function(fonts) {
  var deferred = Q.defer();

  inquirer.prompt([{
    type: 'checkbox',
    name: 'fonts',
    message: 'Select fonts',
    choices: fonts.map(function(font) {
      return font.family;
    })
  }], function(checked) {
    deferred.resolve(checked.fonts);
  });

  return deferred.promise;
};

// Select styles for all fonts
prompts.styles = function(fonts) {
  var deferred = Q.defer(),
      completed = [];

  // recursive helper
  function prompt() {
    var font = null;

    // check whether any fonts
    if(fonts.length) {
      // get next font
      font = fonts.pop();

      // prompt for styles
      prompts.style(font)
      .then(function(font) {
        completed.push(font);
        prompt();
      });

    } else {
      deferred.resolve(completed);
    }
  }

  prompt();
  return deferred.promise;
};

// Select required Styles
prompts.style = function(font) {
  var deferred = Q.defer();

  inquirer.prompt([{
    type: 'checkbox',
    name: 'variants',
    message: 'Select styles',
    choices: font.variants
  }], function(checked) {
    deferred.resolve({
      family: font.family,
      variants: checked.variants
    });
  });

  return deferred.promise;
};
