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

class ForumMessage < ActiveRecord::Base
  belongs_to :forum_user
  #attr_accessible :description, :title, :forum_topic_id, :forum_user, :forum_user_id
  
  validates :description, :presence => true
  
  belongs_to :topic, :class_name => "ForumTopic", :foreign_key => :forum_topic_id
  belongs_to :forum_user
  
  
  
  after_create do
    topic = self.topic
    if topic.forum_messages.count > 1
      
    
      user_to_notify = []
    
      ForumUser.where(:new_messages_notifications => true).each do |forum_user|
      
        user_to_notify << forum_user 
   
        
      end
      FollowedTopic.where(:forum_topic_id => self.forum_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.message_notification(self, forum_user).deliver
      end
    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
end