module AvatarHelper
  
  AVATAR_SIZE="50x50"

  def copy_avatar(des, src)
    src_file = disk_filename(src.class,src.id)
    des_file = disk_filename(des.class,des.id)

    FileUtils.cp(src_file, des_file) if File.exist?(src_file)
  end

  def avatar_image(source, copyed=false)
    source_type = source.class
    source_id = source.id

    # course = Course.find(source_id) rescue nil
    # if course && copyed
    #   source_id  = course.is_copy
    # end
    if source_type.to_s == 'Course' && copyed
      source_id  = source.is_copy
    end

    File.join(relative_path, avatar_directory(source_type), 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 storage_path_coop
    File.join("/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 auth_filename(source_id,type)
    "#{source_id}#{type}"
  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 disk_coo_filename(source_type,source_id,image_file=nil)
    File.join(storage_path_coop,avatar_directory(source_type),avatar_filename(source_id,image_file))
  end

  def disk_auth_filename(source_type,source_id,type)
    File.join(storage_path,avatar_directory(source_type),auth_filename(source_id,type))
  end

  def copy_course?(source_type, source_id)
    file= disk_filename(source_type, source_id)
    if source_type == Course && !File.exist?(file)
      course = Course.find(source_id) rescue nil
      if course && course.is_copy>0
        return true
      end
    end
    false
  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 source.class && source.id && File.exist?(disk_filename(source.class,source.id))
      avatar_image(source, false)
    elsif copy_course?(source.class, source.id)
      get_avatar(Course.find(source.is_copy)) rescue nil
    else
      if source.class.to_s == "User"
        str = source.user_extensions.try(:gender).to_i == 0 ? "b" : "g"
        File.join(relative_path,avatar_directory(source.class), str)
      elsif source.class.to_s == "Shixun"
        File.join("educoder", "index", "shixun", "shixun#{rand(23)}.jpg")
      elsif source.class.to_s == "Subject"
        File.join("educoder", "index", "subject", "subject#{rand(17)}.jpg")
      else
        File.join(relative_path,avatar_directory(source.class), '0')
      end
    end
  end
  
  def get_avatar?(source)
    if source && File.exist?(disk_filename(source.class,source.id))
      return true
    else
      return false
    end    
  end
  
end