require './core/utils/console_prints_utils'
require './core/data/spec_data'

require_relative 'environment/web_environment'
require_relative 'environment/player_ui_environment'
require_relative 'environment/player_core_environment'

module EnvConfig
  include ConsolePrintsUtils

  def initialize_environment
    case ENV['TEST_SUITE']
      when 'player_ui'
        PlayerUIEnvironment.initialize
        Capybara.app_host = PlayerUIEnvironment.url
      when 'player_core'
        PlayerCoreEnvironment.initialize
        Capybara.app_host = PlayerCoreEnvironment.url
      when 'passport'
        # Key is the Passport Environment. Value is the web staging environment
        supported_environments = {'passport-identity-prod' => 'production',
                                  'passport-identity-staging' => 'staging-identity-0'}
        if supported_environments.has_key?(get_environment)
          WebEnvironment.initialize(supported_environments[get_environment]) # Init with the env's associated web env
          Capybara.app_host = WebEnvironment.url
        else
          raise "The passport environment '#{get_environment}' is not currently supported."\
          " Supported environments: #{supported_environments.keys}"
        end
      else
        WebEnvironment.initialize(get_environment)
        Capybara.app_host = WebEnvironment.url
    end
  end

  # @return [String] The environment the tests are running against
  def get_environment
    ENV['ENVIRONMENT']
  end

  def validate_environment(env)
    response = HTTParty.get('http://clean-deploy.internal.justin.tv/v1/repos/web/web/settings')

    if response.code == 200
      body = JSON.parse(response.body)
      environments = body['deploy']['environments']

      if env =~ /clean-(.+)/
        return $1 if environments.has_key?(env) # User included 'clean-'. Deploy api needs it. Send back to capybara without 'clean-'
      else
        return env if environments.has_key?("clean-#{env}") # User didn't include 'clean-'. Send back to capybara without 'clean-'
      end
    end

    return false
  end

  # @return [Boolean] Whether tests are running against production or something else
  def environment_production?
    Capybara.app_host == 'https://www.twitch.tv'
  end

end
