module JamRuby
  class BandInvitation < ActiveRecord::Base

    self.table_name = "band_invitations"

    self.primary_key = 'id'

    BAND_INVITATION_FAN_RECIPIENT_ERROR = "A Band invitation can only be sent to a Musician."

    belongs_to :receiver, :inverse_of => :received_band_invitations, :foreign_key => "user_id", :class_name => "JamRuby::User"
    belongs_to :sender, :inverse_of => :sent_band_invitations, :foreign_key => "creator_id", :class_name => "JamRuby::User"
    belongs_to :band, :inverse_of => :invitations, :foreign_key => "band_id", :class_name => "JamRuby::Band"

    def self.save(id, band_id, user_id, creator_id, accepted)

      band_invitation = BandInvitation.new()

      ActiveRecord::Base.transaction do
        # ensure certain fields are only updated on creation
        if id.nil?
          # ensure recipient is a Musician
          user = User.find(user_id)
          unless user.musician?
            raise JamRuby::JamArgumentError, BAND_INVITATION_FAN_RECIPIENT_ERROR
          end

          band_invitation.band_id = band_id
          band_invitation.user_id = user_id
          band_invitation.creator_id = creator_id

        # only the accepted flag can be updated after initial creation
        else
          band_invitation = BandInvitation.find(id)
          band_invitation.accepted = accepted
        end

        band_invitation.updated_at = Time.now.getutc
        band_invitation.save

        # accept logic => (1) auto-friend each band member and (2) add the musician to the band
        if accepted
          band_musicians = BandMusician.where(:band_id => band_invitation.band.id)
          unless band_musicians.nil?
            band_musicians.each do |bm|
              Friendship.save(band_invitation.receiver.id, bm.user_id)
            end
          end

          # accepting an invitation adds the musician to the band
          BandMusician.create(:band_id => band_invitation.band.id, :user_id => band_invitation.receiver.id, :admin => false)
        end
      end
      return band_invitation
    end
  end
end