module AvatarHelper
  
  AVATAR_SIZE="50x50"
  
  def avatar_image(source)
    File.join(relative_path, avatar_directory(source.class), source.id.to_s) 
  end
     
  def relative_path
    "avatars" #File.join("images","avatars")
  end   
  
  def storage_path 
    File.join(Rails.root, "public", "images", relative_path)
  end
  
  def avatar_directory(source_type)
    "#{source_type}"
  end
  
  def avatar_filename(source_id,image_file)
    "#{source_id}" #<< file_extension(image_file)
  end
  
  def disk_filename(source_type,source_id,image_file=nil)
    File.join(storage_path,avatar_directory(source_type),avatar_filename(source_id,image_file))   
  end
  
  def file_extension(filename=nil)
    $1 if filename =~ %r{(\.[a-zA-Z0-9]+)$}
  end
  
  def get_avatar(source)
    if source.nil? 
      return File.join(relative_path,'AnonymousUser','0')      
    end
    if File.exist?(disk_filename(source.class,source.id))
      avatar_image(source)
    else
      File.join(relative_path,avatar_directory(source.class),'0')
    end    
  end
  
  def get_avatar?(source)
    if File.exist?(disk_filename(source.class,source.id))
      return true
    else
      return false
    end    
  end
  
end
