class AvatarController < ApplicationController

  include ActionView::Helpers::NumberHelper
  #before_filter :set_cache_buster   
  include AvatarHelper

  def upload
    # Make sure that API users get used to set this content type
    # as it won't trigger Rails' automatic parsing of the request body for parameters
    unless request.content_type == 'application/octet-stream'
      @source_type = params[:source_type]
      @source_id = params[:source_id]
      @temp_file = params[:avatar][:image]
      @image_file = @temp_file.original_filename
    else
      unless request.raw_post.nil?
        @source_type = params[:source_type]
        @source_id = params[:source_id]
        @temp_file = request.raw_post
        if @temp_file.size > 0
          if @temp_file.respond_to?(:original_filename)
            @image_file = @temp_file.original_filename
            #image_file.force_encoding("UTF-8") if filename.respond_to?(:force_encoding)
          else
            @image_file=params[:filename]
          end
          @temp_file = StringIO.new(@temp_file)
        end
      end
    end

    if  @temp_file && (@temp_file.size > 0)
      if @temp_file.size > Setting.upload_avatar_max_size.to_i
        @status = 1
        @msg = l(:error_upload_avatar_to_large, :max_size => number_to_human_size(Setting.upload_avatar_max_size.to_i))
      elsif Trustie::Utils::Image.new(@temp_file).image?
        diskfile=disk_filename(@source_type,@source_id)
        @urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))

        # 用户头像上传时进行特别处理
        if  @source_type == 'User'
          diskfile += "temp"
          @urlfile += "temp"
        end

        logger.info("Saving avatar '#{diskfile}' (#{@temp_file.size} bytes)")
        path = File.dirname(diskfile)
        unless File.directory?(path)
          FileUtils.mkdir_p(path)
        end
        md5 = Digest::MD5.new
        File.open(diskfile, "wb") do |f|
          if @temp_file.respond_to?(:read)
            @temp_file.rewind
            buffer = ""
            while (buffer = @temp_file.read(8192))
              f.write(buffer)
              md5.update(buffer)
            end
          else
            f.write(@temp_file)
            md5.update(@temp_file)
          end
        end

        Trustie::Utils::Image.new(diskfile,true).compress(300)
        @status = 0
        @msg = ''
      else
        @status = 2
        @msg = l(:not_valid_image_file)
      end
    end
    @temp_file = nil

    respond_to do |format|
      format.json{
        render :inline => {status: @status, message:@msg, url:"#{@urlfile.to_s}?#{Time.now.to_i}"}.to_json,:content_type => 'text/html'
        return
      }
      format.js
      format.api {
        if saved
          render :action => 'upload', :status => :created
        else
          render_validation_errors(@avatar)
        end
      }
    end
  end

  #add by zjc
  #删除图片
  def delete_image
    @source_type = params[:source_type]
    @source_id = params[:source_id]
    @source = nil #eval(@source_type).find(@source_id)
    c = Object.const_get(@source_type)
    if c.respond_to?(:find)
      @source = c.find(@source_id)
    end

    diskfile=disk_filename(@source_type,@source_id)
    unless diskfile.nil? || diskfile == ""
      path = File.dirname(diskfile)
      if File.directory?(path) && File.exist?(diskfile)
        # 用户头像进行特别处理
        if @source_type == 'User'
          diskfile1 = diskfile + 'temp'
          File.open(diskfile1, "wb") do |f|
            buffer = "DELETE"
            f.write(buffer)
          end
        else
          File.delete(diskfile)
        end
      end
    end
  rescue e do
    logger.info e.message
    end
      respond_to do |format|
        format.js
        format.api {
          if saved
            render :action => 'upload', :status => :created
          else
            render_validation_errors(@avatar)
          end
        }
      end

  end
  
  private
  
    def set_cache_buster  
      response.headers["Cache-Control"] = "no-cache, no-store, max-age=0, must-revalidate"  
      response.headers["Pragma"] = "no-cache"  
      response.headers["Expires"] = "Fri, 01 Jan 1990 00:00:00 GMT"  
    end 


end
