module ActiveModel
  module Translation
    # CarDealer.sales_count -> s_('CarDealer|Sales count') -> 'Sales count' if no translation was found
    def human_attribute_name(attribute, *args)
      s_(gettext_translation_for_attribute_name(attribute))
    end

    def gettext_translation_for_attribute_name(attribute)
      attribute = attribute.to_s
      if attribute.end_with?('_id')
        # foreign keys share the associated model's msgid (see #207)
        gettext_resolve_legacy_msgid(attribute.sub(/_id\z/, '').camelize, humanize_class_name(attribute))
      else
        attribute_key = attribute.split('.').map! {|a| a.humanize }.join('|')
        root = inheritance_tree_root(self).to_s

        # in case of STI or no inheritance, first attempt retrieving the key for the current class
        sti_key = "#{to_s}|#{attribute_key}"
        return sti_key if to_s == root || FastGettext.cached_find(sti_key)

        # fallback to lookup for the root class
        return "#{root}|#{attribute_key}" 
      end
    end

    def inheritance_tree_root(aclass)
      return aclass unless aclass.respond_to?(:base_class)
      base = aclass.base_class
      if base.superclass.abstract_class?
        if defined?(::ApplicationRecord) && base.superclass == ApplicationRecord
          base
        else
          base.superclass
        end
      else
        base
      end
    end

    def humanize_class_name(name=nil)
      name ||= self.to_s
      name.underscore.humanize
    end

    # Canonical msgid for a model name is the raw class name (see #207),
    # e.g. "SomeNamespace::SomeModel" -- consistent with human_attribute_name.
    def gettext_model_name_msgid
      gettext_resolve_legacy_msgid(to_s, humanize_class_name)
    end

    # Returns +current+, unless only the legacy msgid resolves to a
    # translation -- then +legacy+ is returned and a deprecation is warned
    # once. Keeps pre-#207 .po files working during the transition.
    def gettext_resolve_legacy_msgid(current, legacy)
      return current if current == legacy || FastGettext.cached_find(current) || !FastGettext.cached_find(legacy)

      GettextI18nRails.warn_legacy_model_msgid(legacy, current)
      legacy
    end
  end
end
