# -*- encoding : utf-8 -*-

class ForumTopic < ActiveRecord::Base
  belongs_to :forum_user
  #attr_accessible :description, :title, :forum_messages_attributes, :category_id
  has_many :forum_user_topic_vieweds
  
  has_many :followed_topics
  has_many :forum_users, :through => :followed_topics do
    def enabled
      where(":followed_topic.enabled = ?", true)
    end
  end
  
  has_many :active_followers
  has_many :forum_messages
  
  accepts_nested_attributes_for :forum_messages
  

   validates :title, :presence => true
 
  belongs_to :category, :class_name => "ForumCategory"
  
  default_scope { includes(:forum_messages).order("forum_messages.created_at DESC") }
  
	scope :enableds, -> { where(:enabled => true) }
  
  
  #default_scope :include => :forum_messages, :order => "forum_messages.created_at DESC"
  
  after_create do
    topic = self
    
    user_to_notify = []
    
    ForumUser.where(:new_messages_notifications => true).each do |forum_user|
      
      user_to_notify << forum_user 
   
        
    end
    
    ForumUser.where(:new_topic_notifications => true).each do |forum_user|
      
      
      user_to_notify << forum_user
        
    end
    
    ForumUser.where(:follow_new_topics => true).each do |forum_user|
      folowed_topic = forum_user.followed_topics.find_or_initialize_by(:forum_topic_id => topic.id)
      folowed_topic.save
      
        
    end
    
    FollowedTopic.where(:forum_topic_id => topic.id).each do |followed_topic|
      user_to_notify << followed_topic.forum_user
    end
    
    if self.forum_user.follow_participated_topics
      folowed_topic = forum_user.followed_topics.find_or_initialize_by(:forum_topic_id => topic.id)
      folowed_topic.save
    end
    
    
    user_to_notify.uniq!
    
    user_to_notify.each do |forum_user|
      ForumMails.topic_notification(topic, forum_user).deliver
    end
    
  end
  
  def username
    if self.forum_user
    		self.forum_user.firstname.to_s+" "+
    		self.forum_user.name.to_s
    else
    		"utilisateur supprimé"
      end
  end
  
  def principal
    self.forum_messages.order("created_at").first
  end
 
end
