class Edition
  include Mongoid::Document
  include Mongoid::Timestamps
  # This may not be needed as it only exists as part of another whole
  include Mongoid::History::Trackable
  include WorkFlow
  include ActsAsWebPage

  field :bu_content_id, type: String # used to relate editions of same content
  field :version_number, type: Integer, default: 1
  field :title, type: String
  field :description, type: String
  field :slug, type: String, default: ''

  index({ site: 1, slug: 1 })
  index({ slug: 1 })

  alias to_s title

  validates :title, presence: true

  # Allow empty string but not nil for slug
  #  On create ensure that there are only lowercase
  validates :slug, allow_nil: false, format: { with: %r{\A[a-z\d\-\/]*\z} }

  before_validation :set_slug, unless: :slug?
  # This may not be needed as it only exists as part of another whole
  track_history on: :fields, track_create: true, track_update: true,
                track_destroy: true

  def series
    self.class.where(bu_content_id: bu_content_id)
  end

  def history
    series.order(%i[version_number desc])
  end

  def siblings
    series.excludes(id: id)
  end

  def previous_siblings
    siblings.where(:version_number.lt => version_number)
  end

  def subsequent_siblings
    siblings.where(:version_number.gt => version_number)
  end

  def latest_edition?
    subsequent_siblings.empty?
  end

  def published_edition
    series.where(aasm_state: 'published').order(version_number: 'desc').first
  end

  protected

  def set_slug
    # Insure slug is empty string and not nil.
    self.slug ||= ''
  end
end
