module TagsHelper
  def button_to_bulk_tagging(project)
    content = fa_icon("tags", text: t("shared.tag_multiple_releases"))
    disabled_content = fa_icon("spinner spin", text: t("shared.tag_multiple_releases"))
    route = [:new, :bulk_tagging]

    options = {
      id: "tag_all", 
      class: "btn btn-light border mr-2 mb-2", 
      method: :get, 
      remote: true, 
      disabled: true, 
      params: {
        project_id: project,
      },
      data: { 
        disable_with: disabled_content,
      },
      form: {
        data: {
          releasable_ids: [],
        },
      },
    }

    button_to(route, options) { content }
  end

  def tags_preview(taggable, tags)
    TagPreview.new(self, tags, taggable).to_html
  end

  class TagPreview
    def initialize(view, tags, taggable)
      @view = view
      @tags = tags
      @taggable = taggable
    end

    def to_html
      return if tags.empty?

      safe_join [
        names,
        link_to_additional_tags,
      ]
    end

    private

    attr_reader :view, :tags, :taggable

    delegate :content_tag, :link_to, :pluralize, :safe_join, :tag, to: :view

    def two_tags
      tags.first(2)
    end

    def additional_tags
      tags.drop(2)
    end

    def names
      content_tag(:ul, class: "list-inline list-comma-separated fa-ul m-0") do
        two_tags.each do |tag|
          link = link_to_manage_tags(tag.name, class: "small text-nowrap")
          view.concat content_tag(:li, link, class: "list-inline-item")
        end
      end
    end

    def link_to_additional_tags
      return if additional_tags.empty?

      link_to_manage_tags(pluralize(additional_tags.size, "more tag"), class: "badge badge-primary")
    end

    def link_to_manage_tags(content, options = {})
      route = [:new, taggable, :acts_as_taggable_on_tag, locale: I18n.locale]
      opts = {
        remote: true, 
        data: {
          disable_with: content
        }
      }.update(options)

      link_to(content.html_safe, route, opts)
    end
  end
end
