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

    NOTATION_FILE_DIR = "music_session_notations"

    TYPE_NOTATION = 'notation'
    TYPE_AUDIO = 'audio'

    ATTACHMENT_TYPES = [TYPE_NOTATION, TYPE_AUDIO]
    self.primary_key = 'id'

    attr_accessible :file_url, :size, :file_name

    belongs_to :user, :class_name => "JamRuby::User", foreign_key: :user_id
    belongs_to :music_session, :class_name => "JamRuby::MusicSession", foreign_key: :music_session_id

    mount_uploader :file_url, MusicNotationUploader

    before_destroy :delete_s3_files

    #validates :file_url, :presence => true
    validates :attachment_type, :presence => true, inclusion: {in: ATTACHMENT_TYPES}
    validates :size, :presence => true

    def self.create(session_id, type, file, current_user)
      music_notation = MusicNotation.new
      music_notation.attachment_type = type
      music_notation.file_name = file.original_filename
      music_notation.music_session_id = session_id
      music_notation.user = current_user
      music_notation.size = file.size

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

      # now that the model exists (created_at exists), we can save the file in the correct path
      music_notation.file_url = file
      music_notation.save
      music_notation
    end

    def filename
      MusicNotation.construct_filename(self)
    end

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

    def is_notation?
      self.attachment_type == TYPE_NOTATION
    end
    private

    def self.construct_filename(notation)
      "#{NOTATION_FILE_DIR}/#{notation.created_at.strftime('%Y%m%d%H%M%S')}/#{notation.user.id}/#{notation.file_name}"
    end

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