require 'spec_helper'
describe "Music session video button", :js => true, :type => :feature, :capybara_feature => true do
  subject { page }
  let(:user) { FactoryGirl.create(:user, subscription_plan_code: 'jamsubplatinum') }
  let(:connection) { FactoryGirl.create(:connection, :user => user, addr: "1.1.1.1") }
  let(:music_session) {
    ms = FactoryGirl.create(:active_music_session, :creator => user, :musician_access => true)
    ms.save!
    ms
  }
  before(:each) do
    MusicSession.delete_all
    ActiveMusicSession.delete_all
    @url = "/client#/session/#{music_session.id}"
    Gon.global.use_video_conferencing_server = false
  end

  describe "user has opted for video conferencing server" do
    before do
      user.use_video_conferencing_server = true
      user.save!
    end
    
    it "opens video conferencing server page" do
      fast_signin(user, @url)
      # give the web page a little time to connect; sometimes in firefox this needs some time to connect
      page.should_not have_selector('span.disconnected-msg', text: 'DISCONNECTED FROM SERVER')
      execute_script("window.VideoActions.setVideoEnabled(true)") #force video capability of the browser
      # this should open a new window/tab to a different site, as configured by the new
      # Rails.configuration.video_conferencing_host parameter.
      
      temp_tokens_count = JamRuby::TempToken.count

      vid_btn = find(".session-video-btn")

      new_window = window_opened_by { find(".session-video-btn").click() } #assure a new popup window is opened by clicking video button

      within_window new_window do
        expect(TempToken.count).to eq(temp_tokens_count + 1)
      end

      # We only need to verify that secondary window opens up. We should probably also test that a new TempToken record
      # was created as a result of clicking  the video button .I wouldn't bother testing anything else in this particular
      # test.
      #
      # It's true that this secondary window (in staging/production) will load a site that will then in turn call the
      # new controller token auth method.. but we can test the correctness of the new controller method in a much
      # simpler web/spec/controller spec
    end

  end

  describe "user has NOT opted for video conferencing server" do
    before do
      user.use_video_conferencing_server = false
      user.save!
    end

    it "does not open video conferencing server" do
      fast_signin(user, @url)
      # give the web page a little time to connect; sometimes in firefox this needs some time to connect
      page.should_not have_selector('span.disconnected-msg', text: 'DISCONNECTED FROM SERVER')
      execute_script("window.VideoActions.setVideoEnabled(true)") #force video capability of the browser
      
      #assert it does not create new window
      expect { window_opened_by { find(".session-video-btn").click() } }.to raise_error(Capybara::WindowError)
      
     
    end
  end
end