import hashlib

class Avatar(object):
  def __init__(self, app=None):
    self.app = app
    self.state = self._init_app(app)

  def _init_app(self, app):
    return AVATAR_CLASSES[app.config.get('AVATAR_KIND', 'Gravatar')](
      app.config['SERVER_HOSTNAME'],
      app.config['PREFERRED_URL_SCHEME'])

  def __getattr__(self, name):
    return getattr(self.state, name, None)


class BaseAvatar(object):
  """ Base class for all avatar implementations. """
  def __init__(self, server_hostname, preferred_url_scheme):
    self.server_hostname = server_hostname
    self.preferred_url_scheme = preferred_url_scheme

  def get_url(self, email, size=16, name=None):
    """ Returns the full URL for viewing the avatar of the given email address, with
        an optional size.
    """
    raise NotImplementedError

  def compute_hash(self, email, name=None):
    """ Computes the avatar hash for the given email address. If the name is given and a default
        avatar is being computed, the name can be used in place of the email address. """
    raise NotImplementedError


class GravatarAvatar(BaseAvatar):
  """ Avatar system that uses gravatar for generating avatars. """
  def compute_hash(self, email, name=None):
    email = email or ""
    return hashlib.md5(email.strip().lower()).hexdigest()

  def get_url(self, email, size=16, name=None):
    computed = self.compute_hash(email, name=name)
    return '%s://www.gravatar.com/avatar/%s?d=identicon&size=%s' % (self.preferred_url_scheme,
                                                                    computed, size)

class LocalAvatar(BaseAvatar):
  """ Avatar system that uses the local system for generating avatars. """
  def compute_hash(self, email, name=None):
    email = email or ""
    if not name and not email:
      return ''

    prefix = name if name else email
    return prefix[0] + hashlib.md5(email.strip().lower()).hexdigest()

  def get_url(self, email, size=16, name=None):
    computed = self.compute_hash(email, name=name)
    return '%s://%s/avatar/%s?size=%s' % (self.preferred_url_scheme, self.server_hostname,
                                          computed, size)


AVATAR_CLASSES = {
  'gravatar': GravatarAvatar,
  'local': LocalAvatar
}
