class PVolucompteur < ActiveRecord::Base
  
  validates :p_truck_id, :presence => true
  
  belongs_to :p_ship_tour_truck
  #has_one :p_ship_tour, :through => :p_ship_tour_truck
  attr_accessor :write_why, :check_delta
  validates :start_vol, :presence => true
  validates :end_vol, :presence => true
  
  validates :delta_cause, :presence => true, :if => :delta_needed?
  before_validation do
    
    puts "AAAAHHHHHHH"+self.check_delta.to_s
    
  end
  
  after_validation do
    if self.end_vol.to_f < self.start_vol.to_f 
      errors.add(:end_vol, 'doit être supérieur ou égal à la valeur de départ') 
    end
    
    if delta_needed? and !delta_cause?
      self.write_why = true
      errors.add(:end_vol, 'Le volumètre ne correspond pas aux quantités') 
    end
  end
  
  def delta_needed?
    if self.check_delta
    
      if delta_calc_ok != 0
        true
      end
    end
  
  end
  
  def volume_used
    self.end_vol.to_f - self.start_vol.to_f 
  end
  
  def delta_calc
    self.volume_used.to_f - self.p_ship_tour_truck.volume_total_th.to_f
  end
  
  def delta_calc_ok
    self.volume_used.to_f - self.p_ship_tour_truck.volume_total_th_ok.to_f
  end
  
  
  
end
