module JamRuby
  class CrashDump < ActiveRecord::Base

    include JamRuby::S3AnalyticsManagerMixin

    self.table_name = "crash_dumps"

    self.primary_key = 'id'

    belongs_to :user, :inverse_of => :crash_dumps, :class_name => "JamRuby::User"
    
    validates :client_type, :client_version, :description, presence: true

    attr_accessor :user_email

    before_validation(:on => :create) do
      self.created_at ||= Time.now
      self.id = SecureRandom.uuid
      type = description.gsub(/[^a-zA-Z0-9_.-]/, '')
      self.uri = "stats/#{type}/#{created_at.strftime('%Y-%m-%d')}/#{self.id}.zip"
    end
    
    def user_email 
      nil if user_id.nil?
      self.user.email
    end

    def sign_url(expiration_time = 3600 * 24 * 7, secure=true)
      s3_manager.sign_url(self[:uri], {:expires => expiration_time, :secure => secure})
    end

    def read_url
      s3_manager.sign_url(self[:uri], { :expires => Time.now + 5.years,
            :'response_content_type' => 'application/octet-stream'}, :read)
    end

    def write_url
      s3_manager.sign_url(self[:uri], { :expires => Rails.application.config.crash_dump_data_signed_url_timeout,
            :'response_content_type' => 'application/octet-stream'}, :write)
    end

    private

    def s3_bucket
      s3 = AWS::S3.new(:access_key_id => Rails.application.config.aws_access_key_id,
        :secret_access_key => Rails.application.config.aws_secret_access_key)
      s3.buckets[Rails.application.config.aws_analytics_bucket]
    end

  end
end
