module OA
  class CheckOutReleasePage < OA::BasePage
    page_url "/relationships/checkoutrelease"

    h2(:release_approval_heading, text: "Release Approval")
    link(:checked_out_releases, id: "checked-out-releases")
    text_field(:upc, id: "upc")
    select_list(:assigned_to, id: "assigned_to")
    button(:search, id: "searchBtn")

    div(:loader, id: "loader")
    table(:results, class: %w[table table-input-select text-nowrap])
    label(:select_all, for: "selectAll")
    button(:check_out_releases, value: "Check out releases")

    def find_release_by_upc(upc)
      wait_until { !results.blank? }
      populate_search_with_upc(upc)
      submit
    end

    def populate_search_with_upc(upc)
      self.upc = upc
      wait_until { assigned_to_element.option(css: "option[selected]").present? }
      execute_script("arguments[0].outerHTML = ''", assigned_to_element.parent)
      wait_until { !assigned_to? }
    end

    def submit
      search
      # remove this if the grid is too slow to find the loader
      loader_element.when_present(30)
      # Investigate the wait below if it keeps fails.
      # This shouldn't take longer than 60 seconds in QA but as of 10/30/2017,
      # this was bumped up to 120 seconds from 60.
      # As of 10/30/2017, this should not take longer than ~25 seconds in PROD.
      # If it takes longer than that in prod, it's likely that shit code was deployed.
      # loader_element.when_not_present(120)
      check_out_releases_element.when_present(150)
    end
  end
end
