# frozen_string_literal: true

module UxToolkitAttachmentStorageHelper
  def attachment_storage_sort_link(column, caption)
    next_order = (@sort == column.to_s && @order == 'asc') ? 'desc' : 'asc'
    css = @sort == column.to_s ? "sort #{@order}" : 'sort'
    label = if @sort == column.to_s
              safe_join([
                h(caption),
                content_tag(
                  :span,
                  '',
                  class: "ux-toolkit-sort-icon ux-toolkit-sort-icon-#{@order}",
                  aria: {hidden: true}
                )
              ], ' ')
            else
              caption
            end

    link_to label, request.query_parameters.merge(sort: column, order: next_order, page: nil), class: css
  end

  def attachment_storage_status_label(attachment, trash_record)
    status = attachment_storage_status(attachment, trash_record)
    l(:"label_ux_toolkit_attachment_status_#{status}")
  end

  def attachment_storage_status(attachment, trash_record)
    return 'in_trash' if trash_record&.status == UxToolkitAttachmentTrashRecord::STATUS_TRASHED
    return 'permanently_deleted' if trash_record&.status == UxToolkitAttachmentTrashRecord::STATUS_DELETED
    return 'missing' if trash_record&.status == UxToolkitAttachmentTrashRecord::STATUS_MISSING

    RedmineUxToolkit::Services::AttachmentStorage.attachment_status(attachment)
  end

  def ux_toolkit_attachment_container_link(attachment)
    container = attachment.container
    return '-' unless container

    link_to_attachment_container(container) || h(container.to_s)
  rescue StandardError
    h("#{attachment.container_type} ##{attachment.container_id}")
  end
end
