require 'spec_helper'

if defined?(TEST_CONNECT_STATES) && TEST_CONNECT_STATES
  describe "ConnectionStates", :js => true, :type => :feature, :capybara_feature => true do

    before(:all) do
      Capybara.javascript_driver = :poltergeist
      Capybara.current_driver = Capybara.javascript_driver
      @user = FactoryGirl.create(:user)
    end

    it "visits the connection_state test page and let it run its cycle", :js => true do
      visit "/test_connection?user=#{@user.email}&password=foobar"
      page.status_code.should be(200)

      # sleep for the duration of stale+expire delay to give browser time to run through the JS
      sleep_dur = Rails.application.config.websocket_gateway_connect_time_stale + 
        Rails.application.config.websocket_gateway_connect_time_expire 
      # add 1 second each for stale and expire dur used in test_connection; plus 10% buffer
      sleep_dur = (sleep_dur + 2) * 1.1  
      $stdout.puts("*** sleeping for: #{sleep_dur} seconds to allow browser JS to run")
      sleep(sleep_dur)

      # FIXME:  The next step is to process the JS console output and raise assertions
      # as appropriate;  there is currently a database problem wherein inserted Connection records
      # are not found after login; it's prolly an issue with db transactions, but will require more
      # debugging to determine the cause. The connection row is created properly in the login process
      # but when creating music_session, the connection is not found.

      File.exists?(TEST_CONNECT_STATE_JS_CONSOLE).should be_true
      TEST_CONNECT_STATE_JS_CONSOLE_IO.flush

      jsfunctions = %W{ myLoggedIn createMusicSession isStale isExpired }
      jsconsole = File.read(TEST_CONNECT_STATE_JS_CONSOLE)
      jsconsole.split("\n").each do |line|
        next unless line =~ /^#{Regexp.escape(TEST_CONNECT_STATE_JS_LOG_PREFIX)}/
        # $stdout.puts("*** console line = #{line}")
        /ERROR/.match(line).should be_nil

        # FIXME:  do more validation of console output here...
        jsfunctions.delete_if { |fcn| line =~ /#{fcn}/ }
      end 
      jsfunctions.count.should == 0
    end

  end
end
