require 'spec_helper'

describe BroadcastNotification do

  let(:broadcast1) { FactoryGirl.create(:broadcast_notification) }
  let(:broadcast2) { FactoryGirl.create(:broadcast_notification) }
  let(:broadcast3) { FactoryGirl.create(:broadcast_notification) }
  let(:broadcast4) { FactoryGirl.create(:broadcast_notification) }
  let(:user1) { FactoryGirl.create(:user) }
  let(:user2) { FactoryGirl.create(:user) }
  let(:user3) { FactoryGirl.create(:user) }
  let(:user4) { FactoryGirl.create(:user) }

  before(:each) do
    BroadcastNotificationView.delete_all
  end

  it 'created broadcast' do
    expect(broadcast1.title).not_to be_empty
    expect(broadcast1.frequency).to be > 0
  end

  it 'gets view incremented' do
    bnv = broadcast1.did_view(user1)
    bnv = broadcast1.did_view(user1)
    bnv.view_count.should eq(2)
  end

  it 'loads viewable broadcasts for a user' do
    broadcast1.touch
    broadcast2.touch
    broadcast3.touch
    broadcast4.touch

    bns = BroadcastNotification.viewable_notifications(user1)
    bns.length.should eq(4)

    broadcast2.frequency.times { |nn| broadcast2.did_view(user1) }
    broadcast3.did_view(user1)
    broadcast1.did_view(user1)
    broadcast4.did_view(user2)

    bns = BroadcastNotification.viewable_notifications(user1)
    expect(bns.length).to be(3)
    expect(bns[0].id).to eq(broadcast4.id)
    expect(bns.detect {|bb| bb.id==broadcast2.id }).to be_nil
    # now view broadcast 4, since it hasn't been seen, which should bring broadcast 3 up as next since it was seen longest ago
    broadcast4.did_view(user1)
    expect(BroadcastNotification.next_broadcast(user1).id).to eq(broadcast3.id)
  end

  it 'generates frequency distribution' do
    4.times { |nn| broadcast1.did_view(user1) }
    5.times { |nn| broadcast1.did_view(user2) }
    5.times { |nn| broadcast1.did_view(user3) }
    8.times { |nn| broadcast1.did_view(user4) }

    distrib = broadcast1.frequency_distribution

    expect(distrib.count).to be == 3
    expect(distrib[4]).to be == 1
    expect(distrib[5]).to be == 2
    expect(distrib[8]).to be == 1
  end

end
