require 'aws-sdk'
require 'active_support/all'

module JamRuby
  class S3Manager

    SECRET = "krQP3fKpjAtWkApBEJwJJrCZ"

    def self.s3_url(filename)
      "s3://#{aws_bucket}/#{filename}"
    end

    def self.url(filename)
      "https://s3.amazonaws.com/#{aws_bucket}/#{filename}"
    end

    def self.upload_sign(filename, content_md5, upload_id)
      hdt = http_date_time
      str_to_sign = "PUT\n#{content_md5}\n#{content_type}\n#{hdt}\n/#{aws_bucket}/#{filename}"
      signature = Base64.encode64(HMAC::SHA1.digest(aws_secret_key, str_to_sign)).chomp
      { :filename => filename, :signature => signature, :datetime => hdt, :upload_id => upload_id }
    end

    def self.hashed_filename(type, id)
      Digest::SHA1.hexdigest "#{SECRET}_#{type}_#{id}"
    end
  
    def self.multipart_upload_start(upload_filename)
      return 0 if @is_unit_test
      s3_bucket.objects[upload_filename].multipart_upload.id
    end

    def self.multipart_upload_complete(upload_id)
      return if @is_unit_test
      s3_bucket.objects[upload_filename].multipart_uploads[upload_id].upload_complete(:remote_parts)
    end

    def self.delete(filename)
      return if @is_unit_test
      s3_bucket.objects[filename].delete
    end

    def self.set_unit_test
      @is_unit_test = true
    end

    private
    
    def self.s3_bucket
      @s3 ||= AWS::S3.new
      @s3.buckets[aws_bucket]
    end

    def self.aws_bucket
      "jamkazam-dev"
    end

    def self.aws_secret_key
      "XLq2mpJHNyA0bN7GBSdYyF/pWjfzGkDx92b1C+Wv"
    end

    def self.content_type
      "application/octet-stream"
    end

    def self.http_date_time
      Time.now.strftime("%a, %d %b %Y %H:%M:%S %z")
    end


  end
end
