class HipayVirement < ActiveRecord::Base
  belongs_to :devise
  belongs_to :annonce_account
  belongs_to :commission
  has_many :hipay_virement_histories
  validates :hipay_email, :presence => true, :format => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  
  def generate_token
    self.token = loop do
  
   token = SecureRandom.hex(6)
     break token unless Virement.exists?(token: token)
   end
   
   self.token
  end
  
  
  before_validation do
    if self.annonce_account.hipay_virements.where("sended is null").count >= 1 or self.annonce_account.virements.where("sended is null").count >= 1
      errors.add(:amount_ht, "Vous ne pouvez pas avoir plus d'un virements en attente d'execution.")
    end

    
    if self.amount_ht.to_f < 5 or self.amount_ht.to_f > self.annonce_account.max_virement(self.devise_id)
    errors.add(:amount_ht, "Le montant doit être compris entre 5 € et #{self.annonce_account.max_hipay_virement(self.devise_id).to_i} €")
    
    end
  end
  
  
end
