class ForumPost < ActiveRecord::Base
  attr_accessible :content, :reply_to, :quote_to

  # associations
  belongs_to :user
  belongs_to :reply, class_name: 'ForumPost', foreign_key: 'reply_to'
  belongs_to :quote, class_name: 'ForumPost', foreign_key: 'quote_to'
  belongs_to :topic, class_name: 'ForumTopic', foreign_key: 'forum_topic_id', counter_cache: :posts_count, touch: :last_post_at
  has_many :attachments, as: :attachable, dependent: :destroy
  accepts_nested_attributes_for :attachments, reject_if: :all_blank, allow_destroy: true
  has_and_belongs_to_many :users
  has_and_belongs_to_many :likers, class_name: 'User', join_table: 'forum_posts_likers', association_foreign_key: 'liker_id'

  # callbacks
  before_create :write_quote
  after_create :notify_new_post

  # validations
  validates :content, presence: true

  # delegates
  delegate :name, :email, :avatar, :highlight_posts?, to: :user, allow_nil: true, prefix: true
  delegate :content, to: :quote, allow_nil: true, prefix: true
  delegate :forum_private?, :name, to: :topic, allow_nil: true, prefix: true

  # scopes
  scope :active, where(active: true)

  # methods
  def write_quote
    self.featured = true if user_highlight_posts?
    if self.quote
      self.content = "<blockquote>#{self.quote_content}</blockquote>#{self.content}"
    end
  end

  def notify_new_post
    # if forum is private, notify all users that there is a new topic
    if topic_forum_private?
      user_emails = topic.users.map(&:email)
      user_emails -= Array.wrap(user_email)
      UserMailer.notify_new_forum_post(self, user_emails).deliver
    end
  end

  def seen_by
    @seen_by ||= users.map(&:name).to_sentence
  end

  def name
    content
  end
end
