# -*- encoding : utf-8 -*-
class Comment < ActiveRecord::Base

  include ActsAsCommentable::Comment

  belongs_to :commentable, :polymorphic => true

 	validates :pseudo, :presence => true
	validates :email, :presence => true, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  validates :comment, :presence => true
  
  belongs_to :lang_site

	scope :recents, -> {where("enabled = ?",true ).order("created_at ASC")}


  acts_as_tree
  after_create do
    Comment.notify
  end
    
    
  def self.notify
    last_notify = Comment.order("notified_at DESC").first.notified_at
    
    comments_not_notifieds = Comment.where("enabled is null or enabled = 0").where(:notified => false)
    
    if comments_not_notifieds.count >= 10 or last_notify <= Time.now-1.day
      self.notify_news
      
      comments_not_notifieds.update_all( :notified => true, :notified_at => Time.now)
    end
    
  end
  
  
  def self.notify_news
    puts "On notifie"
    
    AdminMailer.notify_comments().deliver
    
  end

end
