require './core/base/spec_helper'
require './core/configs/bmp_config'
require './core/utils/console_prints_utils'
require './core/network_traffic_analytics/video_player/tier1_event_filtering'
require './core/api/video_player/stream_metadata_api'
require './core/twitch/video_player/player_page'
require './core/network_traffic_analytics/filtering'

include ConsolePrintsUtils

player_url = VideoPlayerData.player_stream_url
player_domain = VideoPlayerData.player_domain
player_channel = VideoPlayerData.player_channel
player_host = VideoPlayerData.player_host
buffer_refill_schema = '/video_player/tier1_events/buffer_refill_schema'

feature 'Validating Network Tracked Tier 1 Events - BUFFER REFILL:' do
  let(:tier1) { Tier1EventFiltering.new }
  let(:player) { PlayerPage.new('stream') }
  let(:network_traffic) { Filtering.new(get_proxy) }

  before(:all) do
    @proxy = get_proxy
    StreamMetadataApi.get_stream_metadata(player_channel)
  end

  scenario "'buffer-refill' fired after bandwith was limited and then lifted upon landing on player." do

    expected_event = {
      'buffer-refill' => [true, buffer_refill_schema, player_url, player_host, player_domain, player_channel]
    }

    PlayerPage.visit_with_localstore_settings(player_url)
    sleep(10) # Waiting 10 seconds for the video to load up and ad to finish before limiting the bandwidth.
    @proxy.new_har

    @proxy.limit_proxy_bandwidth(10000, 0, 0) # Adding 10 seconds latency, 250kbs downstream, 50kbs upstream.
    PlayerPage.fluent_wait_stats_display(1, 10) # Debuggin for buffering events. See Smoc-337.

    @proxy.limit_proxy_bandwidth(0, 0, 0) # Remove added latency, downstreamKbps, and upstreamKpbs
    PlayerPage.fluent_wait_stats_display(1, 10) # Debuggin for buffering events. See Smoc-337.

    spade_events = network_traffic.filter_spade_events
    event = tier1.get_buffer_refill_event(spade_events)

    begin
      expect(event).to eq(expected_event)
    rescue RSpec::Expectations::ExpectationNotMetError => e
      puts "Encountered error #{e.class}.\nSpade Events: #{spade_events}\nStats: #{PlayerPage.get_player_stats}"
      TwitchUtils.debug_logging(network_traffic.get_json_har, "buffer_refill")
      raise e
    end
  end

end
