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

include LoggerUtils

feature 'Playback Stats' do

  let(:player_url) { PlayerCoreData.player_core_url }
  let(:vod_url) { "#{PlayerCoreData.player_core_domain_for_vod}/videos/#{TwitchUtils.vod_id(VideoPlayerData.player_vod)}.m3u8" }

  scenario 'can get a valid playback stats for VOD stream', :unsupported_browsers => [:edge, :internet_explorer] do
    # BUG CVP-1438 for edge and IE
    visit player_url
    expect(PlayerCore).to have_video_container
    expect(PlayerCore.stream_started?(vod_url)).to be_truthy

    attempts = 0
    max_attempts = 2

    begin
      attempts += 1
      playback_stats = PlayerCore.playback_stats_values
      playback_stats.each_with_index do |stat, index|
        expect(stat).to be > 0.0, "Expected #{index} - #{stat} to be > 0 in #{playback_stats}"
      end
    rescue RSpec::Expectations::ExpectationNotMetError => e
      # Race condition - sometimes we can call getVideoFrameRate() 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
      if attempts < max_attempts
        logger.warn("[Attempt #{attempts}/#{max_attempts}] Encountered an unexpected number within #{playback_stats}. Retrying...")
        sleep 3
        retry
      else
        logger.debug('Reached max attempts')
        raise e # Max attempts reached, raise error
      end
    end
  end
end
