class KapsDay < ActiveRecord::Base
  belongs_to :p_customer
  
  has_many :kapsmes
  has_many :kaps_rappels, :through => :kapsmes
  
  after_save do
    
    
    generate_kapsmes
    


    
    
  end
  
  def generate_kapsmes
    #self.kapsmes.where(:kap_id => 1).destroy_all
    self.p_customer.kaps.where(:kaps_type_id => 1).where("start_at <= ? and (end_at is null or end_at >= ?)", self.date, self.date).each do |kap|
      
      
      
      
      if !self.kapsmes.where(:kap_id => kap.id).first
        
        if kap.active_days
          if last_paused_kapsme = self.p_customer.kapsmes.where(:kap_id => kap.id, :paused => true).joins(:kaps_day).order("kaps_days.date DESC").first    
            #sdffs = sfsf
            #start_date = nil
            start_date = kap.start_at
          else
            start_date = kap.start_at
          
          end
        
          dif = (self.date - start_date).to_i % (kap.active_days+kap.pause_days)
        
          if dif < kap.active_days
            paused = false
          else
            paused = true
          end
          
        else
          paused = false
        end
        
        self.kapsmes.create(
          :kap_id => kap.id,
          :paused => paused,
          :name => kap.name,
          :description => kap.description,
          :public => kap.public,
          :kaps_cat_id => kap.kaps_cat_id,
          :kaps_type_id => kap.kaps_type_id,
          
          :points => kap.points,
      
          :origin_kaps_id => kap.origin_kaps_id,
          :origin_author_id => kap.origin_author_id,
          :archived => kap.archived,
          :kaps_day_id => self.id,
        
        
          :p_customer => self.p_customer
        )
      
      
      
      end
      
      
    end
  end
  
  
  def total_points
    self.kapsmes.sum(:point_to_count)
  end
  
  def total_points_earneds
    self.kapsmes.where(:done => true).sum(:points)
  end
  
  
  def completed
    (100.0 * self.total_points_earneds.to_f) / total_points.to_f
    
  end
  
  
  def self.cron
    PCustomer.all.each do |pc|
      pc.generate_kaps_days
    end
    
    # whenever --update-crontab
  end
  
  
end
