class PShipTourTruck < ActiveRecord::Base
  belongs_to :p_ship_tour
  belongs_to :p_truck
  belongs_to :p_driver
  
  has_many :p_ship_spaces, :dependent => :destroy
  
  accepts_nested_attributes_for :p_ship_spaces, allow_destroy: true
  
  
  
  validates :p_truck_id, :presence => true
  #validates :comment, :presence => true
  
  
  belongs_to :p_ship_tour_truck
  
  has_many :p_ship_tour_trucks
  
  has_many :p_sheet_lines, :through => :p_ship_tour_truck_sheet_lines
  
  has_many :p_ship_tour_truck_sheet_lines, :dependent => :destroy
  accepts_nested_attributes_for :p_ship_tour_truck_sheet_lines
  
  
  has_many :p_volucompteurs, :dependent => :destroy
  accepts_nested_attributes_for :p_volucompteurs, allow_destroy: true
  validates_associated :p_volucompteurs
  
  after_validation do
    self.p_volucompteurs.each do |child|
      child.valid?
    end
  end
  
  def volume_total_th
    var = 0.0
    
    volumes_th.each do |index, value|
      var += value.to_f
    end
    
    return var
  end
  
  def volume_total_th_ok
    var = 0.0
    
    volumes_th_ok.each do |index, value|
      var += value.to_f
      puts "AAAAHHHHH#{value}"
    end
    
    return var
  end
  
  def volumes_th
    var = {}
    
    self.p_sheet_lines.each do |p_sheet_line|
      var[p_sheet_line.p_product_id.to_s] = var[p_sheet_line.p_product_id].to_f + p_sheet_line.qte
      
    end
    
    return var
  end
  
  
  def volumes_th_ok
    var = {}
    
    self.p_ship_tour_truck_sheet_lines.each do |p_ship_tour_truck_sheet_line|
      var[p_ship_tour_truck_sheet_line.p_sheet_line.p_product_id.to_s] = var[p_ship_tour_truck_sheet_line.p_sheet_line.p_product_id].to_f + p_ship_tour_truck_sheet_line.qte_shiped.to_f
      
    end
    
    return var
  end
  
  before_validation do 
    self.set_remorques
    
  end
  
  
  after_create do
    self.set_remorques
  end
  
  def set_remorques 
   # dfdsf = sdffsd
    if self.tracteur_id and self.p_ship_tour 
      t = self.p_ship_tour.p_ship_tour_trucks.where(:p_truck_id => self.tracteur_id).first
      if t
        self.p_ship_tour_truck_id = t.id
      end
    end
    
    #self.remorque = self.p_truck.remorque if self.p_truck
  end
end
