module JamRuby
  class JoinRequest < ActiveRecord::Base

    REQUESTOR_MUST_BE_A_MUSICIAN = "requestor must be a musician"

    self.primary_key = 'id'

    belongs_to :user, :class_name => "JamRuby::User"
    belongs_to :music_session, :class_name => "JamRuby::MusicSession"
    has_many :invitations, :inverse_of => :join_request, :class_name => "JamRuby::Invitation"

    validates :user, :presence => true
    validates :music_session, :presence => true
    validates :text, presence: false, no_profanity: true, length: {maximum: 140} #  arbitrary decision of 140.  the database is at 2000 max on this field

    validates_uniqueness_of :user_id, :scope => :music_session_id

    validate :requestor_is_musician

    # list all paginations for the current user
    def self.index(current_user)
      # TODO pagination
      return JoinRequest.where("join_requests.user_id = '#{current_user.id}'").order('join_requests.created_at DESC')
    end

    def requestor_is_musician
      unless user.musician?
        errors.add(:user, REQUESTOR_MUST_BE_A_MUSICIAN)
      end
    end

    def to_s
      return "#{self.user.to_s}:#{self.music_session.to_s}"
    end


  # permissions:
  # only the creator of the join request can do a get
  # or a member of the music_session that the join_request is designated for
    def self.show(id, user)
      return JoinRequest.find(id, :conditions => ["user_id = ? OR music_session_id IN (select music_session_id from connections WHERE user_id = ?)", user.id, user.id])
    end
  end
end
