module JamRuby
  class UserAsset < ActiveRecord::Base
    include JamRuby::S3ManagerMixin

    self.table_name = "user_assets"
    self.primary_key = 'id'

    belongs_to :user, :inverse_of => :user_assets, :class_name => "JamRuby::User"
    validates :asset_type, :filename, :uri, presence: true

    #TODO: validate asset_type
    #asset_type - a varchar - but effectively an enum in the ruby code.  We should, but don’t have to set the list of valid types here.  if we do, we might consider actually using Rails config instead of in the record code.

    before_validation(on: :create) do
      self.created_at ||= Time.now
      self.id = SecureRandom.uuid
      self.uri = "/user_assets/#{self.asset_type}/#{created_at.strftime('%Y-%m-%d')}/#{filename_no_ext}-#{self.id}#{filename_ext}"
    end

    def filename_no_ext
      File.basename(filename, '.*')
    end

    def filename_ext
      File.extname(filename)
    end

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

    def write_url
      s3_manager.sign_url(self[:uri], { :expires => Rails.application.config.user_asset_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_bucket]
    end

  end
end
