module Workstation
  class ManageRightsPage < Workstation::BasePage
    page_url "/managerights"

    button(:generate_download_link, id: "generate")
    button(:download_template, id: "download")
    file_field(:select_file_button, id: "fileupload")
    link(:upload, id: "uploadButton")

    # Track counts in Overview widget
    div(:incomplete_tracks_text, class: "incomplete")
    em(:incomplete_tracks_num) { incomplete_tracks_text_element.em_element }
    div(:complete_tracks_text, class: "complete")
    em(:complete_tracks_num) { complete_tracks_text_element.em_element }

    # Last Upload widget
    div(:check_for_complete, id: "status-processed")

    # Errors
    div(:alert_bar, id: "alert_bar")

    def upload_complete?
      check_for_complete_element.when_present.attribute("class").include?("active")
    end

    def generate
      generate_download_link
      wait_until { download_template_element.disabled? }
    end

    def template_url
      wait_until(120) { download_template_element.enabled? }
      grab_s3_public_url(download_template_element)
    end

    def upload_file(filename)
      fail "file does not exist at path: #{filename}" unless File.exist?(filename)
      # wait for track count to appear before attempting upload
      incomplete_tracks_num_element.when_present(60)
      wait_until { select_file_button_element.enabled? }
      select_file_button_element.element.set(filename)
      upload_element.click
    end
  end
end
