class ForumTopic < ActiveRecord::Base
  attr_accessible :name, :posts_count, :posts_attributes

  # associations
  belongs_to :user
  belongs_to :forum, counter_cache: :topics_count, touch: true
  has_many :posts, class_name: 'ForumPost', dependent: :destroy
  has_many :visits, class_name: 'ForumTopicVisit', dependent: :destroy
  accepts_nested_attributes_for :posts, allow_destroy: true
  has_and_belongs_to_many :users

  # validations
  validates :name, presence: true, length: { maximum: 200 }

  # delegates
  delegate :name, :email, to: :user, allow_nil: true, prefix: true
  delegate :name, :private?, to: :forum, allow_nil: true, prefix: true

  # callbacks
  after_create :notify_new_topic

  # FriendlyId
  extend FriendlyId
  friendly_id :name, :use => [:slugged, :history]

  # methods
  def users_count
    visits.count
  end

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

  def new_posts(user)
    return 0 unless user
    @new_posts ||= (post_ids - user.forum_post_ids).size
  end
end
