require_relative 'environment_config'
require './core/data/video_player_data'
require './core/data/spec_data'

# Builds the necessary URL variables
# player_host, player_base_url, player_stream_url
# See variable descriptions in VideoPlayerData
class PlayerUIEnvironment < EnvironmentConfig

  class << self

    attr_reader :url

    # Configure Player UI Environment and stores the URL.
    def initialize
      build_player_urls
      @url = VideoPlayerData.player_stream_url + ' & ' + VideoPlayerData.player_vod_url
    end

    # Configures player_host and player_stream_url based on validate player parameters.
    private def build_player_urls
      validate_player_parameters

      # Build the URL for Capybara to use.
      # An example layout: https://betaplayer.twitch.tv/?channel=monstercat

      # Start with the Host & Base
      VideoPlayerData.player_host = "#{VideoPlayerData.player_environment}.#{VideoPlayerData.player_domain}" # ex. betaplayer.twitch.tv
      VideoPlayerData.player_base_url = "https://#{VideoPlayerData.player_host}/" # ex. https://betaplayer.twitch.tv
      set_testplayer_branch # Configure testplayer url if applicable. ex. https://testplayer.twitch.tv/my_branch/

      # Append the channel to the url
      VideoPlayerData.player_stream_url = "#{VideoPlayerData.player_base_url}?channel=#{VideoPlayerData.player_channel}"

      build_vod_url
      check_player_type
    end

    # Configure player_url_stream if player_branch is specified and player_environment is testplayer.
    private def set_testplayer_branch
      if !VideoPlayerData.player_branch.nil? && VideoPlayerData.player_environment == 'testplayer'
        # If branch provided, add it to the url. Ex: https://testplayer.twitch.tv/my_branch/
        VideoPlayerData.player_base_url += "#{VideoPlayerData.player_branch}/"
      end
    end

    # Configures VOD url based off of player_stream_url
    private def build_vod_url
      split_url = VideoPlayerData.player_stream_url.split(/channel=/)
      base_url = split_url[0]
      VideoPlayerData.player_vod_url = base_url + "video=#{VideoPlayerData.player_vod}"
    end

    # Specific check to ensure hls_fallback is only used for safari.
    private def check_player_type
      if !VideoPlayerData.player_type.nil?

        if VideoPlayerData.player_type == 'hls_fallback' && SpecData.browser != 'safari'
          raise "'Browser' must be 'safari' for parameter 'hls_fallback' to work."
        end

      end
    end

    # If user provided a environment equal to 'testplayer', branch must also be specified. If not, raise an error.
    private def validate_player_parameters
      if VideoPlayerData.player_branch.nil? && VideoPlayerData.player_environment == 'testplayer'
        raise "Error. PLAYER_ENVIRONMENT 'testplayer' requires PLAYER_BRANCH. Please provide PLAYER_BRANCH"
      end
    end

  end
end
