class PProductBrutStock < ActiveRecord::Base
  belongs_to :p_brut_product
  belongs_to :p_fournisseur_order
  belongs_to :p_tank
  
  validates :p_brut_product, :presence => true
  validates :p_tank_id, :presence => true, :if => :validate_tank?
  
  
	scope :oks, -> {where(:ok => true).order("ok_at DESC")}
  scope :not_oks, -> {where(:ok => false).order("ok_at DESC")}
	
	scope :between, lambda { |start, stop|
	        after(start).before(stop)
	    }
	
	scope :after, lambda { |date|
	        where("(ok_at >= ?)", date )
	    }
	scope :before, lambda { |date|
	        where("(ok_at <= ?)", date )
	    }
  
  validates :ok_at, :presence => true, :if => :validate_ok?
  validates :ok_price, :presence => true, :if => :validate_ok?
  validates :ok_qte, :presence => true, :if => :validate_ok?

  before_validation do 
    if validate_tank?
      errors.add(:p_tank_id, 'doit correspondre au produit') if self.p_brut_product and self.p_tank and self.p_tank.p_brut_product and self.p_tank.p_brut_product != self.p_brut_product
    
    else
      self.p_tank = nil
    
    end
    
    
    
  end
  
  after_save do
    if self.ok and !self.lock
      self.qte_restant = self.ok_qte
      self.lock = true
      self.save
    end
  end
  
  def validate_ok?
    if self.ok
      true
    else
      false
    end
  end
  
  def validate_tank?
    if self.externe
      false
    else
      true
    end
  end

end
