'use strict';

var _ = require('lodash');
var util = require('util');
var contra = require('contra');
var request = require('request');
var mkdirp = require('mkdirp');
var gravatarService = require('../../../services/gravatar');
var cache = {};

mkdirp.sync('temp/gravatars');

module.exports = function (req, res, next) {
  var resources = req.body.resources;

  contra.map(resources, 2, fetch, concat);

  function fetch (resource, next) {
    if (cache[resource]) {
      ok();
    } else {
      gravatarService.fetch(resource, true, add);
    }
    function add (err, result) {
      if (err) {
        next(err); return;
      }
      cache[resource] = result;
      ok();
    }
    function ok () {
      next(null, cache[resource]);
    }
  }

  function concat (err, results) {
    if (err) {
      res.status(500).json({}); return;
    }
    var images = results.map(toData).reduce(asKey, {});
    res.json({ images: images });
  }

  function toData (result) {
    return util.format('data:%s;base64,%s', result.mime, result.data);
  }

  function asKey (accumulator, item, i) {
    accumulator[resources[i]] = item;
    return accumulator;
  }
};

@@ -133,22 +133,25 @@
 ');%0Avar 
-mkdirp
+validator
  = requi
@@ -154,22 +154,25 @@
 equire('
-mkdirp
+validator
 ');%0Avar 
@@ -249,40 +249,8 @@
 %7D;%0A%0A
-mkdirp.sync('temp/gravatars');%0A%0A
 modu
@@ -296,16 +296,47 @@
 %7B%0A  var 
+input = Array.isArray(req.body.
 resource
@@ -336,18 +336,19 @@
 esources
- =
+) ?
  req.bod
@@ -358,16 +358,78 @@
 esources
+ : %5B%5D;%0A  var resources = _.uniq(input.map(validator.toString))
 ;%0A%0A  con

validate input, only process each url once