require 'spec_helper'

describe 'MusicSessionReminder' do
  let(:mail) { UserMailer.deliveries[0] }
  before :each do
    UserMailer.deliveries.clear
    MusicSession.delete_all
    User.delete_all

    @receiver = FactoryGirl.create(:user)
    @sender = FactoryGirl.create(:user)
    @session = FactoryGirl.create(:music_session)

    @slot1 = FactoryGirl.build(:rsvp_slot, :music_session => @session, :instrument => JamRuby::Instrument.find('electric guitar'))
    @slot1.save

    @slot2 = FactoryGirl.build(:rsvp_slot, :music_session => @session, :instrument => JamRuby::Instrument.find('drums'))
    @slot2.save
  end

  it "sends email 24 hours before" do
    @session.creator = @sender
    @session.scheduled_start = Time.now + 23.hours
    @session.save!

    JamRuby::MusicSessionReminder.perform

    UserMailer.deliveries.length.should == 1
    calls = count_publish_to_user_calls
    calls[:count].should == 0

    mail.html_part.body.include?("is scheduled for tomorrow").should be_true
    mail.text_part.body.include?("is scheduled for tomorrow").should be_true

    mail.html_part.body.include?("starts in 1 hour").should be_false
    mail.text_part.body.include?("starts in 1 hour").should be_false
  end

  it "sends email 1 hour before" do
    @session.creator = @sender
    @session.scheduled_start = Time.now + 59.minutes
    @session.save!


    JamRuby::MusicSessionReminder.perform

    UserMailer.deliveries.length.should == 1
    calls = count_publish_to_user_calls
    calls[:count].should == 0
    mail.html_part.body.include?("is scheduled for tomorrow").should be_false
    mail.text_part.body.include?("is scheduled for tomorrow").should be_false

    mail.html_part.body.include?("starts in 1 hour").should be_true
    mail.text_part.body.include?("starts in 1 hour").should be_true

  end

  it "sends notice 5 minutes before" do
    UserMailer.deliveries.length.should == 0
    receiver_connection = FactoryGirl.create(:connection, user: @receiver)
    @receiver.reload

    rsvp = RsvpRequest.create({:session_id => @session.id, :rsvp_slots => [@slot1.id, @slot2.id], :message => "We be jammin!"}, @receiver)
    UserMailer.deliveries.clear
    calls = count_publish_to_user_calls
    @session.creator = @sender
    @session.scheduled_start = Time.now + 4.minutes
    @session.save!
    JamRuby::MusicSessionReminder.perform
    calls[:count].should == 1
    UserMailer.deliveries.length.should == 0
  end

  def count_publish_to_user_calls
    result = {count: 0}
    MQRouter.any_instance.stub(:publish_to_user) do |receiver_id, msg|
      result[:count] += 1
      result[:msg] = msg
    end
    result
  end
end #spec
