class KapsRappel < ActiveRecord::Base
  belongs_to :kap
  
  def self.generate_rappels
    puts "AAAAAAHHHH"
    
    KapsDay.where(:date => Date.today).each do |kd|
      kd.kaps_rappels.where("hour <= ?", Time.now.hour).each do |kr|
        
        kr.generate_rappel(kd,Time.now)
        
      
      end
      
    end
    
  end
  
  def generate_rappel(kaps_day, time)
    if kaps_rappel_items = KapsRappelItem.where(:kaps_rappel_id => self.id, :kaps_day_id => kaps_day.id) and count = kaps_rappel_items.count and count < (self.nbr_rep.to_i + 1)
      
      if kapsme = kaps_day.kapsmes.where(:kap_id => self.kap_id).first and ((!kapsme.done and !kapsme.paused) or (!kapsme.done and self.paused_inc)) 
        if kaps_rappel_items.count == 0 or (time > kaps_rappel_items.order("created_at DESC").first.created_at + (self.minutes_rep.to_i >= 15 ? self.minutes_rep.to_i : 15).minutes)
          KapsRappelItem.create(:kaps_rappel_id => self.id, :kaps_day_id => kaps_day.id, :kapsme_id => kaps_day.kapsmes.where(:kap_id => self.kap_id).first.id, :number => (count + 1))
      
        end
      end
      
      puts "Un Rappel est lancé"
    else
      puts "RAPPEL"
      puts count
      puts "Rappel déjà fait"
    
    end
    
    
    
  end
  
  
  
  
  
end
