module HasTags
  extend ActiveSupport::Concern

  included do

    scope :tagged_with, ->(tag) { tagged_with_any(tag) }
    scope :all_or_tagged_with, ->(tag) { tagged_with_any(tag) if tag }

    scope :tagged_with_any, ->(tags) { where("tags -> '#{I18n.locale}' ?| ARRAY[:tags]", tags: tags) }
    scope :tagged_with_all, ->(tags) { where("tags @> ?", {"#{I18n.locale}": [tags].flatten}.to_json) }

  end


  # def descendant_tags
  #   return self.class.tags unless self.respond_to?(:descendants)
  #
  #   result = {}
  #   I18n.available_locales.each { |l| result[l] = [] }
  #
  #   self.descendants.viewable.pluck(:tags).flatten.map do |tags|
  #     tags.each do |k,v|
  #       result[k.to_sym] += v
  #     end
  #   end
  #   result.each{ |k, v| result[k] = v.flatten.uniq.sort }
  # end


  module ClassMethods

    # def tags
    #   result = {}
    #   I18n.available_locales.map.each { |l| result[l] = [] }
    #
    #   pluck(:tags).flatten.map do |tags|
    #     tags.each do |k,v|
    #       result[k.to_sym] += v
    #     end
    #   end
    #   result.each{ |k, v| result[k] = v.flatten.uniq.sort }
    # end

  end



end
