Given(/^PENDING/) do
  pending
end

And(/^I refresh the page$/) do
  @browser.refresh
end

When(/^I use my browser's back button$/) do
  @browser.back
end

When(/^I wait (\d+) seconds$/) do |wait|
  sleep wait.to_i
end

# Regex matches a phrase like "OA::RelationshipsPage" or "Workstation::HeatmapPage"
When(/^I (am on|visit) the (\w+::\w+)$/) do |_keyword, class_as_string|
  # if class_as_string = "Workstation::HeatmapPage"
  # this will call: visit(Workstation::HeatmapPage)

  # using reflection because otherwise this is a massive case-switch statement
  # rubocop:disable Custom/AvoidReflection
  if @session_token
    visit_and_dismiss_alerts(
      Object.const_get(class_as_string),
      using_params: { queries: @url_queries }
    )
  else
    visit_and_dismiss_alerts(Object.const_get(class_as_string))
  end
  # rubocop:enable Custom/AvoidReflection
end

When(/^I (am on|visit) the (\w+::\w+) as a (.*?) user$/) do |_keyword, class_as_string, user_name|
  user_name = user_name.to_sym
  workstation_user_data = DataHelpers::UserConfig.lookup(:workstation, user_name)
  @users.record_workstation_user(name: user_name,
                                 user_data: workstation_user_data)
  @session_token = Support::Services::GrassAuth.instance.workstation_session_token(user_name)
  # using reflection because otherwise this is a massive case-switch statement
  # rubocop:disable Custom/AvoidReflection
  visit(Object.const_get(class_as_string), using_params: { queries: @url_queries })
  # rubocop:enable Custom/AvoidReflection
end

Given(/^an OA (\S+) user$/) do |user_name|
  user_name = user_name.to_sym
  oa_user_data = DataHelpers::UserConfig.lookup(:oa, user_name)
  id_query = "SELECT id FROM orchadmin_users WHERE email = '#{oa_user_data[:email]}'"
  oa_user_data[:id] = Support::DbClient.query_art_relations(id_query).first["id"]
  @users.record_oa_user(name: user_name,
                        user_data: oa_user_data)

  on(OA::BasePage) do |page|
    # get on valid OA page
    page.goto unless page.current_url.include?(page.page_url_value) &&
                     page.valid_login_header? && on(OA::LoginPage).error_message? == false
  end
  @browser.alert.ok if @browser.alert.exists?
  # don't need to do anything if we're already logged in as the correct user
  unless on(OA::LoginPage).on_login_form?
    next if on(OA::BasePage).user_full_name == oa_user_data[:vendor_name] # already logged in as desired user
    # logout if we're logged in as the wrong user
    on(OA::BasePage).logout_link
  end
  if !MISC_SETTINGS[:tfa_whitelisted]
    login_to_oa_with_valid_token(oa_user_data)
  else
    on(OA::LoginPage) do |page|
      page.goto if page.error_message?
      page.login_with_user_data(oa_user_data)
    end
  end
  expect(on(OA::BasePage).user_full_name).to eql oa_user_data[:vendor_name]
end

Given(/^the (.*?) feature control is (.*?) for (\S+)$/) do |feature, state, user_name|
  query = "SELECT feature_id FROM features WHERE feature_name = '#{feature}'"
  feature_id = Support::DbClient.query_art_relations(query).first["feature_id"]
  vendor_id = user_name.split("_").last
  query = "SELECT * FROM vendor_restricted_features WHERE vendor_id = #{vendor_id}"
  case state
  when "enabled"
    if Support::DbClient.query_art_relations(query).any? { |row| row["feature_id"] == feature_id.to_i }
      step "an OA Technology_manager user"
      visit(OA::EditVendorPage, using_params: { queries: { "vendor_id" => vendor_id } }) do |page|
        page.enable_feature_control(feature)
      end
    end
  when "disabled"
    if Support::DbClient.query_art_relations(query).none? { |row| row["feature_id"] == feature_id.to_i }
      step "an OA Technology_manager user"
      visit(OA::EditVendorPage, using_params: { queries: { "vendor_id" => vendor_id } }) do |page|
        page.disable_feature_control(feature)
      end
    end
  end
end

# rubocop:disable Metrics/BlockLength
Given(/^a Workstation (\S+) user$/) do |user_name|
  user_name = user_name.to_sym
  workstation_user_data = DataHelpers::UserConfig.lookup(:workstation, user_name)
  @users.record_workstation_user(name: user_name,
                                 user_data: workstation_user_data)
  on(Workstation::BasePage) do |page|
    # get on valid Workstation page
    unless (page.current_url.include?(page.page_url_value) && page.valid_login_header?) ||
           (page.current_url.include?(page.page_url_value) &&
               on(ReactWorkstation::ReactHomePage).label_name_dropdown?)
      page.goto
    end
  end

  # don't need to do anything if we're already logged in as the correct user
  unless on(Workstation::LoginPage).login_form?
    next if on(Workstation::BasePage).logged_in_as?(workstation_user_data)
    on(Workstation::BasePage) do |page|
      # logout if we're logged in as the wrong user
      # this is a workaround for a bug with the logout process
      # TODO: see if this is fixed with WSR
      begin
        page.logout
      rescue Selenium::WebDriver::Error::UnknownError # if unclickable
        if page.url.include? "modal"
          visit(Workstation::BasePage)
        else
          page.refresh
        end
        page.logout
      end
    end
    @browser.alert.ok if @browser.alert.exists?
    on(Workstation::LoginPage).login_form_element.when_present
  end
  on(Workstation::LoginPage) do |page|
    page.login_with_user_data(workstation_user_data)
    # When attempting to log in again as a different workstation user on the same chrome instance,
    # clicking the log in button again sometimes just refreshed the login page instead of actually
    # logging in, likely due to the speed that cucumber logs in and out. This attempts to log in
    # again to account for that non-real-world scenario.
    page.wait_until { !page.login_form? }
    page.login_with_user_data(workstation_user_data) if page.username?
  end
  expect(on(Workstation::BasePage).logged_in_as?(workstation_user_data)).to be true
end
# rubocop:enable Metrics/BlockLength

Given(/^a standalone Workstation (\S+) user$/) do |user_name|
  user_name = user_name.to_sym
  workstation_user_data = DataHelpers::UserConfig.lookup(:workstation, user_name)
  @users.record_workstation_user(name: user_name,
                                 user_data: workstation_user_data)
  @session_token = Support::Services::GrassAuth.instance.workstation_session_token(user_name)
  @url_queries = { "session" => @session_token }
end

Given(/^I am logged into workstation on production$/) do
  workstation_user_data = DataHelpers::UserConfig.lookup(:workstation, :prod)
  visit(Workstation::LoginPage).login_with_user_data(workstation_user_data)
  @users.record_workstation_user(
    name: :prod,
    user_data: workstation_user_data
  )
  on(Workstation::LoginPage) do |page|
    page.wait_until { !page.login_form? }
  end
end

And(/I start the timer/) do
  @start = Time.now.to_f
end

And(/I stop the timer/) do
  endd = Time.now.to_f
  total_time = endd - @start
  total_time = (total_time * 1000).to_i
  puts @start
  puts endd
  puts "total time: #{total_time} ms"
end

And(/I stop and log the timer/) do
  endd = Time.now.to_f
  total_time = endd - @start
  total_time = (total_time * 1000).to_i
  puts @start
  puts endd
  puts "total time: #{total_time} ms"
  File.open("logs/timer.txt", "a") { |file| file.write("#{total_time} \n") }
end

# Feature control
Given(/^(\S+) is disabled$/) do |feature|
  disable_via_cookie feature
end

Given(/^(\S+) is enabled$/) do |feature|
  enable_via_cookie feature
end

And(/^I collect any JS errors on the page$/) do
  fail "plugin only works on firefox" unless BROWSER.firefox?
  errors = @browser.execute_script("return window.JSErrorCollector_errors.pump()")

  if errors.any?
    puts "Found #{errors.length} javascript error(s)"

    errors.each do |error|
      puts " | #{error['errorMessage']} (#{error['sourceName']}:#{error['lineNumber']})"
    end
  end
end

# rubocop:disable Metrics/BlockLength
# Feb 28, 2019: This block is getting pretty long. Might be a better way to do this.
Given(
  /^the active variant for (.*) is (.*) on (.*)$/
) do |feature_name, variant_name, platform|
  user = case platform
         when "workstation"
           @users.workstation_user
         when "OA"
           @users.oa_user
         when "frontend-distribution"
           @users.distribution_user
         when "physical-reporting"
           @users.reporting_user
         when "sales-sheets"
           @users.sales_sheets_user
         when "source-of-streams"
           @users.source_of_streams_user
         when "accounting-statements"
           @users.accounting_user
         when "accounting-d3-statements"
           @users.accounting_user(:accounting_d3)
         when "accounting-sub-statements"
           @users.accounting_user(:accounting_sub)
         when "conflict-manager"
           @users.conflict_manager_user
         when "video"
           @users.video_user
         when "users"
           @users.users_user
         when "workstation-spa"
           @users.workstation_spa_user
         else
           fail "unknown platform: '#{platform}'!"
         end
  user.update_active_variant_for_feature(feature_name, variant_name)
end
# rubocop:enable Metrics/BlockLength

# below steps can only be used on workstation SPA standalone environment
Given(/^the feature flag (.*) is enabled$/) do |feature_name|
  if @session_token
    @url_queries[:enabled_feature_flag] ||= []
    @url_queries[:enabled_feature_flag] << feature_name
  end
end

Given(/^the feature flag (.*) is disabled$/) do |feature_name|
  if @session_token
    @url_queries[:disabled_feature_flag] ||= []
    @url_queries[:disabled_feature_flag] << feature_name
  end
end

Given(/^the vendor restriction for (.*) is enabled$/) do |feature_name|
  if @session_token
    @url_queries[:vendor_restricted_feature] ||= []
    @url_queries[:vendor_restricted_feature] << feature_name
  end
end

Given(/^I delete all rejection and release data associated with my product$/) do
  Support::Helpers::Queries.delete_rejection_notes(@product_id)
  Support::Helpers::Queries.delete_release_approval_queue(@product_id)
  Support::Helpers::Queries.delete_release_correction_detail(@product_id)
  Support::Helpers::Queries.delete_release_correction(@product_id)
end

Then(/^I should see permission denied error/) do
  expect(@browser.h1.text).to include "Sorry, you don't have access to this page."
  expect(@browser.url).to include "/alw/error/permission"
end
