require './core/base/page_helper'
require './core/twitch/video_player/player_page'
require './core/twitch/video_player/player_ui_events'

class PlayerUI < PageHelper
  @settings_menu        = '.pl-menu'
  @quality_text         = 'Quality'
  @video_quality_text   = 'Video Quality'
  @playback_stats_table = '.js-playback-stats'
  @player_loading_spinner = '#js-loading-overlay .pl-loading-spinner'

  class << self
    include PlayerUIEvents
    # @return [Hash] Returns all the available options of the video
    def available_quality_options
      quality_options = page.execute_script('return player.getQualities()')
      expect(quality_options.size).to be > 0
      return quality_options
    end

    # @return [Hash] Key value pair of playback stats
    def playback_stats_values
      return page.execute_script('return player.getPlaybackStats()')
    end

    # Opens the setting menu of the player
    def open_settings_menu
      PlayerPage.settings_btn.click unless page.has_selector?(@settings_menu)
      expect(page).to have_selector(@settings_menu)
    end

    # @param quality [Hash] Quality attributes
    def set_quality_from_ui(quality)
      open_settings_menu
      quality = quality['name'] if quality.is_a? Hash
      within(@settings_menu) do
        click_on @quality_text
        expect(page).to have_text(@video_quality_text)
        click_on quality
      end
    end

    def show_advanced_stats
      open_settings_menu
      within(@settings_menu) do
        click_on 'Advanced'
        click_on 'Show Video Stats'
      end
      expect(page).to have_selector(@playback_stats_table)
    end

    # @return [Array] Stats displayed on the player page
    def ui_stats
      playback_stat = []
      within(@playback_stats_table) do
        stats = all('li')
        stats.each { |stat| playback_stat << stat.find('span').text }
      end
      return playback_stat
    end

    # @param position [Integer] Point to seek to in the VoD
    def seek_to_position(position)
      page.execute_script("player.setCurrentTime(#{position})")
    end

    # @return [Boolean] If the playback has started
    def playback_started?
      page.has_selector?(@player_loading_spinner, wait: 10)
      return page.has_no_selector?(@player_loading_spinner, wait: 10)
    end
  end
end
