require 'rotp'

class GoogleSSOPage < BasePage
  h1(:heading, id: "headingText")
  div(:next_button) do
    span_element(text: "Next").parent
  end
  text_field(:email_field, type: 'email')
  text_field(:password, type: "password")
  text_field(:enter_code, css: "input[aria-label='Enter code']")
  span(:try_another_way, text: 'Try another way')
  strong(:google_auth, text: 'Google Authenticator')
  span(:login_success, id: 'logoText', text: 'OAuth 2.0')

  def google_sso_login(email, password, authenticator_key)
    login_with_authenticator(email, password, authenticator_key)
    @browser.goto('https://cms.youtube.com')
  end

  def login_with_authenticator(email, password, authenticator_key)
    enter_email(email)
    enter_password(password)
    enter_otp(authenticator_key)
    wait_until { login_success_element.when_present }
  end

  def enter_otp(authenticator_key)
    wait_until { heading_element.text.downcase == "2-step verification" }
    google_auth_element.when_present.click
    wait_until { enter_code_element.when_present }
    otp = ROTP::TOTP.new(authenticator_key).now
    self.enter_code = otp
    begin
      retries ||= 0
      next_button_element.when_present.click
    rescue Selenium::WebDriver::Error::ElementClickInterceptedError
      retry if (retries += 1) < 3
    end
  end

  def enter_password(password)
    wait_until { heading_element.text.downcase == "welcome" }
    self.password = password
    next_button_element.click
  end

  def enter_email(email)
    wait_until { email_field_element.when_present }
    self.email_field = email
    next_button_element.click
  end

  def choose_account(google_account)
    div_element(id: "profileIdentifier", text: google_account).click
  end
end

