class GenericObject
  include Mongoid::Document
  include Mongoid::History::Trackable
  include RelatesObjectTags
  include HasPresentationData

  field :title, type: String
  field :slug, type: String
  field :type, type: String  # This gets overwritten by the template title on save
  field :body, type: String

  validates :title, presence: true, uniqueness: {scope: :type}
  validates :slug, presence: true, uniqueness: {scope: :type}
  validates :type, presence: true

  before_validation :set_object_type

  track_history on: :fields, track_create: true, track_update: true, track_destroy: true

  scope :custom_search, -> query {
    begin
      if query.present?
        q = ::Regexp.new(query.to_s, 'i')
        any_of({ title: q })
      end
    rescue ::RegexpError
      GenericObject.none
    end
  }

  def set_object_type
    # Don't overwrite the type if there is no related template.
    if template_title = presentation_data_template.try(:title)
      self.type = template_title
    end
  end

end
