require "digest/md5"

class Aggravatar::Gravatar
  attr_reader :email

  def initialize(email, params = {})
    @email  = email
    @params = params
  end

  def email_hash
    Digest::MD5.hexdigest email
  end

  def url
    build_url "www.gravatar.com"
  end

  def secure_url
    build_url "secure.gravatar.com", URI::HTTPS
  end

  private
  def avatar_path
    "/avatar/#{email_hash}"
  end

  def build_query
    URI.encode_www_form normalized_params
  end

  def build_url(host, builder = URI::HTTP)
    uri = builder.build(
      host: host,
      path: avatar_path
    )

    uri.query = build_query unless @params.empty?

    uri.to_s
  end

  def normalized_params
    params = @params.dup

    if params.delete(:force_default)
      params[:forcedefault] = "y"
    end

    params
  end
end
