module Dunlop::TableHelper
  def search_row(options = {}, &blk)
    classes = Array.wrap(options[:class])
    classes |= ['search']
    classes << 'conditions-present' if @q.conditions.present?
    content = capture(&blk)
    content_tag(:tr, content,  class: classes )
  end

  # This helper returns the link for showing a record inside a table
  def table_show_link(record, path = nil, options = {})
    if options.has_key?(:authorized)
      return unless options[:authorized]
    else
      return unless can? :show, record
    end
    link_to(content_tag(:i,nil, class: 'folder open icon'), path || record, class: 'table-link show ui mini basic primary icon button')
  end

  # This helper returns the link for showing a record inside a table
  def table_download_link(record, path = nil, options = {})
    if options.has_key?(:authorized)
      return unless options[:authorized]
    else
      return unless can? :download, record
    end
    link_to(content_tag(:i,nil, class: 'download icon'), path || [:download, record], class: 'table-link download ui mini violet icon button')
  end

  # This helper returns the link for editing a record inside a table
  def table_edit_link(record, path = nil, options = {})
    if options.has_key?(:authorized)
      return unless options[:authorized]
    else
      return unless can? :update, record
    end
    link_to(content_tag(:i, nil, class: 'write icon'), path || [:edit, record], class: 'table-link edit ui mini basic yellow icon button')
  end

  def table_destroy_link(record, path = nil, options = {})
    if options.has_key?(:authorized)
      return unless options[:authorized]
    else
      return unless can? :destroy, record
    end
    confirm_text = "Are you sure you want to delete #{record.class.model_name.human}"
    record_name = nil
    record_name = record.presentation_name if record.respond_to?(:presentation_name)
    record_name ||= record.name if record.respond_to?(:name)
    record_name ||= record.title if record.respond_to?(:title)
    confirm_text << " #{record_name}" if record_name.present?
    confirm_text << "?"
    link_to(content_tag(:i, nil, class: 'trash icon'), path || record, method: :delete, data: { confirm: confirm_text }, class: 'table-link destroy ui mini negative icon button')
  end
end
