require './core/base/spec_helper'
require './core/twitch/video_player/player_core'
require './core/utils/logger_utils'

include LoggerUtils

feature 'Validating streaming ' do
  player_url = PlayerCoreData.player_core_url
  let(:fps) { 30 }
  let(:audio_only) { 'audio' }

  before(:each) do
    visit player_url
    # Checking if stream can be paused
    expect(page).to have_css(PlayerCore.video_container, wait: 5)
    expect(PlayerCore.stream_started?).to be_truthy
  end

  scenario "resolution with its height", :unsupported_browsers => [:internet_explorer, :firefox] do
    PlayerCore.available_quality_options.each do |quality|
      expect(PlayerCore.set_quality?(quality.text)).to be_truthy
      curr_quality = PlayerCore.current_quality
      expect(curr_quality['name'].to_i).to eql(curr_quality['height'].to_i)
    end
  end

  scenario 'encoder latency is always less than broadcaster latency' do
    encoder_lantecy = PlayerCore.get_encoder_latency
    # If the returned value for encoder latency is 0, retry...
    if encoder_lantecy == 0
      # Race condition - sometimes we can call get_encoder_latency too quick after load, in which it returns 0
      # Sleep for 3 seconds and try again. More detail: https://twitch.slack.com/archives/C1BFYM8P2/p1524782484000240
      logger.warn("Received #{encoder_lantecy} for get_encoder_latency. Sleeping and then retrying...")
      sleep(3)
      encoder_lantecy = PlayerCore.get_encoder_latency
    end

    expect(encoder_lantecy).to be < PlayerCore.get_broadcaster_latency
  end

  scenario 'fps remains around 30 when playing at normal rate at different qualities' do
    skip 'BUG : CVP-1741'
    PlayerCore.available_quality_options.each do |quality|
      next if quality.text.downcase.include? audio_only
      expect(PlayerCore.set_quality?(quality.text)).to be_truthy
      expect(PlayerCore.get_fps).to be_within(2).of(fps), "expected #{PlayerCore.get_fps} to be around #{fps} for quality-#{quality.text}"
    end
  end

end
