module ResourceHelper
  def res_link_show(obj, opts = {})
    if defined? can?
      can? :show, obj or return ''
    end
    label = fa_icon :search, title: t('res_actions.show', default: 'Show')
    if {show_text_label: true}.merge(opts)[:show_text_label]
      label += ' '.html_safe + t('res_actions.show')
    end
    link_to label, obj, class: 'ar-action btn btn-secondary btn-sm'
  end

  def res_link_edit(obj, opts = {})
    if defined? can?
      can? :update, obj or return ''
    end
    label = fa_icon :edit, title: t('res_actions.edit', default: 'Edit')
    if {show_text_label: true}.merge(opts)[:show_text_label]
      label += ' '.html_safe + t('res_actions.edit')
    end
    link_to label, edit_polymorphic_path(obj), class: 'ar-action btn btn-secondary btn-sm'
  end

  def res_actions(obj, opts = {})
    opts = {:actions => [:edit, :destroy], :show_text_label => true}.merge opts
    btns = []
    opts[:actions].member? :show and
      btns.push res_link_show(obj, opts)
    opts[:actions].member? :edit and
      btns.push res_link_edit(obj, opts)
    opts[:actions].member? :destroy and
      btns.push res_link_destroy(obj, opts)
    content_tag :span, btns.join(' ').html_safe, class: 'ar-actions'
  end

  def res_label(obj, field)
    t "activerecord.attributes.#{(Class === obj.class ? obj.name : obj.class.name).underscore}.#{field}"
  end

  def res_name(obj)
    obj or return ''
    obj.respond_to?(:name) and return obj.name
    "#{t "activerecord.objs.#{obj.class.name.underscore}"} ##{obj.id}"
  end
end
