module Project
  # The artwork page should only have very small differences between physical
  # and digital, so we can use the same page for both. This can be separated
  # later if need be.
  class ProductArtworkPage < BasePage
    include ProductFooter
    include ProductSidebar

    page_url "/project/<%=params[:project_id]%>/product/<%=params[:product_id]%>/artwork"

    div(:missing_information_alert, class: "DismissibleAlert-danger")

    section(:artwork_section, class: "ArtworkUploadV2")
    div(:artwork_dropzone, class: "ArtworkUploadV2-dropzone")
    file_field(:artwork) { artwork_dropzone_element.file_field_element }
    svg(:loader, class: "Icons-loading-ring")
    button(:save, id: "digital-product-footer-next-button")
    div(:upload_success, class: "ArtworkUploadV2-status-bar")
    div(:invalid_image_error, class: "ArtworkUploadV2-status-bar-invalid-image")

    # We don't click this but we want to wait until it is visible before our upload workaround
    button(:replace_artwork, class: "ArtworkUploadV2-replace-button")

    def current_artwork_url
      fail "Artwork element not on page!" unless upload_success?

      background_image_style = upload_success_element.element.style "background-image"
      background_image = background_image_style.split(", ").first # second image is undefined
      background_image.match(/^url\("(.*)"\)$/)[1] # matches "url("#{url}")"
    end

    def upload_artwork(file)
      upload_workaround(element: artwork_element, path: file)
    end

    def wait_for_replace_artwork_button
      wait_until { replace_artwork_element.present? }
    end

    def wait_for_success
      # there's a brief wait between the loader disappearing and the upload success element
      wait_until(300) { upload_success_element.text == "ARTWORK COMPLETE" }
    end
  end
end
