class Forum < ActiveRecord::Base
  attr_accessible :name, :private, :description

  # associations
  belongs_to :forum_category, counter_cache: :forums_count
  has_many :topics, class_name: 'ForumTopic', dependent: :destroy
  belongs_to :user
  has_and_belongs_to_many :users

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

  # delegates
  delegate :name, to: :user, allow_nil: true, prefix: true

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

  # callbacks
  after_save :ensure_forum_permissions

  # methods
  def self.for_user current_user
    if current_user.can? :manage, Forum
      scoped.order('forums.updated_at DESC')
    else
      scoped.where('forums.id in (?) or forums.private = 0', current_user.forum_ids)
    end
  end

  def new_posts(user)
    return 0 unless user
    @new_posts ||= ( topics.map{|t| t.new_posts(user) }.inject(:+) || 0 )
  end

  def ensure_forum_permissions
    if self.private?
      forum_permissions = Permission.where(subject_class: 'Forum', action: ['read', 'participate'])
      users.each do |u|
        forum_permissions.each do |p|
          PermissionsRole.where(role_id: u.role_id, permission_id: p.id).first_or_create
        end
      end
    end
  end
end
