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

    self.table_name = 'mobile_recording_uploads'
    self.primary_key = 'id'

    RECORDING_FILE_DIR = "mobile_recording_uploads"

    attr_accessible :file_url, :size, :file_name

    belongs_to :mobile_recording,
               class_name: "JamRuby::MobileRecording",
               foreign_key: :mobile_recording_id

    mount_uploader :file_url, MobileRecordingUploader

    before_destroy :delete_s3_files

    validates :size, :presence => true

    def self.create(mobile_recording, file, file_name)
      mru = self.new
      mru.file_name = file_name
      mru.mobile_recording = mobile_recording
      mru.size = file.size

      # save first to get a valid created_at time
      mru.save!

      # CarrierWave says we need a file extension, doesn't get provided
      tmpfile = Tempfile.new([file_name, File.extname(file_name)])
      tmpfile.write(file)
      
      # now that the model exists (created_at exists), we can save the file in the correct path
      mru.file_url = tmpfile
      mru.save
      mru
    end

    def filename
      self.class.construct_filename(self)
    end

    def sign_url(expiration_time = 120)
      s3_manager.sign_url(self[:file_url], {:expires => expiration_time, :secure => true})
    end

    private

    def self.construct_filename(mru)
      "#{RECORDING_FILE_DIR}/#{mru.created_at.strftime('%Y%m%d%H%M%S')}/#{mru.mobile_recording.user_id}/#{mru.file_name}"
    end

    def delete_s3_files
      s3_manager({:public => true}).delete(self[:file_url]) if self[:file_url]
    end
  end
end
