class MOdrFileRoulage < ApplicationRecord
  belongs_to :m_odr_file
  belongs_to :m_event

  validates :date, :presence => true

  before_validation do
    self.nbr_primes = 2
    
    self.nbr_primes_not_useds = self.nbr_primes - nbr_primes_useds


  end


  def generate_prime
    prime_ids = []
    if nbr_primes_to_use = self.nbr_primes_not_useds and nbr_primes_to_use > 0


      if achats = MOdrFile.where(:admin_ok => true, :p_customer_id => self.m_odr_file.p_customer_id,:m_odr_file_type_id => 2).where("buy_at <= ? and nbr_pneus_not_useds > 0", self.date) and (achats.sum(:nbr_pneus_not_useds) > 0)   
        
        state =  "A traiter"
        
        prime = MOdrPrime.new(:state => state, :m_odr_file_roulage => self, :p_customer_id => self.m_odr_file.p_customer_id)
        n_tot = 0
        achats.each do |a|
          if n_tot < nbr_primes_to_use
            if (nbr_primes_to_use - n_tot) <= a.nbr_pneus_not_useds
              n = (nbr_primes_to_use - n_tot)

            else
              n = a.nbr_pneus_not_useds
            end

            prime.m_odr_prime_files.build(:m_odr_file => a, :nbr_pneus => n, :amount => n*15.0)

            a.nbr_pneus_useds = a.nbr_pneus_useds.to_i + n

            prime.save
            a.save

            prime_ids << prime.id

            n_tot = n_tot + n

            self.nbr_primes_useds = self.nbr_primes_useds.to_i + n
            self.save
          end
        end
      end
    end

    prime_ids = prime_ids.uniq

    MOdrPrime.where(:id => prime_ids).all.each do |p|
      p.send_init_mail
    end
  end

end
