require 'spec_helper'

describe 'Feeds' do

  subject { page }

  before(:each) do
    MusicSession.delete_all
    Recording.delete_all
    Diagnostic.delete_all
    User.delete_all
  end

  let(:admin) { FactoryGirl.create(:admin) }
  let(:user) { FactoryGirl.create(:user) }

  let(:music_session) { FactoryGirl.create(:music_session, :creator => user) }
  let(:recording)     { FactoryGirl.create(:recording_with_track, :owner => user) }
  let(:diagnostic)    { FactoryGirl.create(:diagnostic, :user => user) }

  context 'empty dashboard' do
    before(:each) do
      visit admin_feed_path
    end

    it { should have_selector('h2', text: 'Feed') }

    it 'has no feeds' do
      should_not have_selector('h3', text: 'Music Sessions - All')
      should_not have_selector('h3', text: 'Recordings - All')
      should_not have_selector('h3', text: 'Diagnostics - All')
    end
  end


  context 'admin enters a user name' do
    before(:each) do
      user.touch
      visit admin_feed_path
    end

    it 'auto-completes with email + full name', :js => true do

      within('form.feed') do
        fill_in 'feed_user', with: user.email[0..3]
      end

      page.execute_script %Q{ $('form.feed input#feed_user').trigger('focus') }
      page.execute_script %Q{ $('form.feed input#feed_user').trigger('keydown') }
      find('a.ui-corner-all', text: user.to_label).trigger(:click)
      should have_selector('form.feed #feed_user', user.to_label)
      should have_selector('form.feed #feed_user_id[value="' + user.id + '"]', visible:false)
    end
  end

  context 'with existing activities' do
    before(:each) do
      music_session.touch
      recording.touch
      diagnostic.touch
      visit admin_feed_path
    end

    it 'shows session, recording, diagnostic' do
      should have_selector("tr#jam_ruby_music_session_#{music_session.id}")
      should have_selector("tr#jam_ruby_recording_#{recording.id}")
      should have_selector("tr#jam_ruby_diagnostic_#{diagnostic.id}")
    end

    it 'shows activities for one user', :js => true do
      within('form.feed') do
        fill_in 'feed_user', with: user.email[0..3]
      end

      page.execute_script %Q{ $('form.feed input#feed_user').trigger('focus') }
      page.execute_script %Q{ $('form.feed input#feed_user').trigger('keydown') }
      find('a.ui-corner-all', text: user.to_label).trigger(:click)
      should have_selector('form.feed #feed_user', user.to_label)
      should have_selector('form.feed #feed_user_id[value="' + user.id + '"]', visible:false)

      page.execute_script %Q{ $('form.feed').trigger('submit') }
      
      should have_selector("tr#jam_ruby_music_session_#{music_session.id}")
      should have_selector("tr#jam_ruby_recording_#{recording.id}")
      should have_selector("tr#jam_ruby_diagnostic_#{diagnostic.id}")
    end
  end
end