/**
 * Service which provides helper methods for retrieving the avatars displayed in the app.
 */
angular.module('quay').factory('AvatarService', ['Config', '$sanitize', 'md5',
    function(Config, $sanitize, md5) {
  var avatarService = {};
  var cache = {};

  avatarService.getAvatar = function(hash, opt_size) {
    var size = opt_size || 16;
    switch (Config['AVATAR_KIND']) {
      case 'local':
        return '/avatar/' + hash + '?size=' + size;
        break;

      case 'gravatar':
        return '//www.gravatar.com/avatar/' + hash + '?d=404&size=' + size;
        break;
    }
  };

  avatarService.computeHash = function(opt_email, opt_name) {
    var email = opt_email || '';
    var name = opt_name || '';

    var cacheKey = email + ':' + name;
    if (!cacheKey) { return '-'; }

    if (cache[cacheKey]) {
      return cache[cacheKey];
    }

    var hash = md5.createHash(email.toString().toLowerCase());
    switch (Config['AVATAR_KIND']) {
      case 'local':
        if (name) {
          hash = name[0] + hash;
        } else if (email) {
          hash = email[0] + hash;
        }
        break;
    }

    return cache[cacheKey] = hash;
  };

  return avatarService;
}]);