module VulgataMethods
  extend ActiveSupport::Concern

  included do
    class_attribute :vlg_priority, :vlg_strategy, :vlg_context_path, :vlg_context_path_param, :vlg_skip_pendify, :vlg_after_translated, :vlg_after_approved, :vlg_preprocess_setter, :vlg_preprocess_getter, :vlg_skip_init
    has_many :translation_states, class_name: 'Vulgata::TranslationState', as: :item
  end

  module ClassMethods
    def vulgata_priority
      vlg_priority
    end

    def vulgata_after_translated
      vlg_after_translated
    end

    def vulgata_name
      @vlg_name ||= to_s.underscore.humanize
    end

    def vulgata_source_scope(items)
      vlg_strategy.scope_by_source_items items
    end

    # returns array of the translated attributes names
    def vulgata_translated_attribute_names
      vlg_strategy.translated_attribute_names self
    end

    # returns all the translation that contains a given string
    def vulgata_where_like(query_string, collection = nil)
      query = vulgata_translated_attribute_names.map { |key| "%{table_name}.#{key} LIKE :q" }.join(' OR ')
      query_params = { q: "%#{query_string}%" }
      vlg_strategy.where_like_query self, query, query_params, collection
    end
  end

  def vulgata_after_approved
    vlg_after_approved.blank? ? nil : send(vlg_after_approved)
  end

  def vulgata_preprocess_setter(data)
    vlg_preprocess_setter.blank? ? data.delete_if { |_k, v| v.blank? } : send(vlg_preprocess_setter, data)
  end

  def vulgata_preprocess_getter(data)
    vlg_preprocess_getter.blank? ? data : send(vlg_preprocess_getter, data)
  end

  # returns array of the translated attributes names
  def vulgata_translated_attribute_names
    self.class.vulgata_translated_attribute_names
  end

  # returns hash of the translated data
  def vulgata_translation_data(translation_state)
    vlg_strategy.translation_data translation_state
  end

  def vulgata_save_translation(translation_state)
    vlg_strategy.save_translation translation_state
  end

  def vulgata_item_type
    self.class.base_class.name
  end

  def vulgata_name
    self[:name] || self[:title] || self[:subject] || self[:description] || self[:body] || self[:text] || to_s
  end

  def vulgata_priority
    @vlg_priority || vlg_priority
  end

  def vulgata_priority=(value)
    @vlg_priority = value
  end

  # name of path helper for the object's context - i.e :blog_post_path (for a Comment object)
  def vulgata_context_path
    vlg_context_path
  end

  # name of param to send to path helper - property of associated object - i.e :post (for a Comment object)
  def vulgata_context_path_param
    vlg_context_path_param
  end
end
