require "yaml"
require "addressable/uri"

module World
  module FeatureControlHelpers
    # Set an 'enabled' cookie for the given feature
    # Example: Impersonate workstation login for label 22572 then call
    # enable_via_cookie('workstation_experience') to set a cookie that will enable
    # "Workstation Experience" for this film label
    def enable_via_cookie(feature)
      return if feature_enabled? feature
      set_cookie(feature, "enabled")
    end

    def disable_via_cookie(feature)
      return if feature_disabled? feature
      set_cookie(feature, "control")
    end

    # Public: Controls what a test does if a feature is enabled
    #
    # feature - The feature we want to check if enabled
    #
    # Example
    #
    #   if feature_enabled? "workstation_redesign_for_users"
    #     @browser.click_new_audio_button
    #   else
    #     @browser.click_old_audio_button
    #   end
    #
    # Returns boolean
    def feature_enabled?(feature)
      cookies = BROWSER.cookies.map(&:strip)
      cookies.include? "features[#{feature}]=enabled"
    end

    def feature_disabled?(feature)
      cookies = BROWSER.cookies.map(&:strip)
      cookies.include? "features[#{feature}]=control"
    end

    # Public: Controls what a test does if a platform feature is enabled
    #
    # feature - The feature we want to check if enabled
    #
    # Example
    #
    #   if platform_feature_enabled?("frontend-distribution", "display_upc")
    #     @browser.get_new_upc
    #   else
    #     @browser.get_old_upc
    #   end
    #
    # Returns boolean
    def platform_feature_enabled?(platform, feature)
      user = case platform
             when "workstation"
               @users.workstation_user
             when "OA"
               @users.oa_user
             when "frontend-distribution"
               @users.distribution_user
             when "source-of-streams"
               @users.source_of_streams_user
             else
               fail "unknown platform: '#{platform}'!"
             end
      user.feature_variance_enabled? feature
    end

    private

    def set_cookie(feature, variant, cookie = "1")
      uri = Addressable::URI.parse(@browser.url)
      # Use Array of [key, value] pairs in order to
      # preserve param order: http://stackoverflow.com/a/24695485/3456726
      initial_query = uri.query_values ? uri.query_values.to_a : []
      uri.query_values = initial_query + [
        ["feature", feature],
        ["feature_variant", variant],
        ["feature_cookie", cookie]
      ]
      @browser.goto(uri.to_s)
      check_for_fatal_error
    end

    def check_for_fatal_error
      fail(
        "Could not set feature control cookie!\n #{@browser.text}"
      ) if @browser.b(text: /^fatal error$/i).present?
    end
  end
end
