class ProductOrderDocument < ActiveRecord::Base
  belongs_to :product_order
  belongs_to :product_order_document_type
  
  after_create do
    generate_number
  end
  
  before_validation do
    self.verify
    if !self.id
      puts "TTTT"
      puts ProductOrderDocument.where(:product_order_id => self.product_order_id,:product_order_document_type_id => self.product_order_document_type_id).count
    
      #sdffdsfds = sffds
      if ProductOrderDocument.where(:product_order_id => self.product_order_id,:product_order_document_type_id => self.product_order_document_type_id).count > 0
      
        #sdfsd = sdfdsfsdf
        errors.add(:product_order_id, 'Le document existe déjà')
      end
    end
  end
  
  def generate_number

    
    if !self.d_number
      
      self.d_year = self.product_order.created_at.year
      
      self.public = self.product_order_document_type.public
      self.d_prefix = self.product_order_document_type.prefix.to_s
      self.label = self.product_order_document_type.label.to_s
      self.header = self.product_order_document_type.header.to_s
      self.footer = self.product_order_document_type.footer.to_s
      self.image_file_id = self.product_order_document_type.image_file_id
      self.data_file_id = self.product_order_document_type.data_file_id
      self.reseaux_id = self.product_order_document_type.reseaux_id
      self.fournisseur_id = self.product_order_document_type.fournisseur_id
      self.name = self.product_order_document_type.name
      
      last_number = 0
      last_dt = ProductOrderDocument.where("d_number is not null").where(:d_year => self.d_year,:product_order_document_type_id => self.product_order_document_type_id).order("d_index DESC").first
      #sdfdfs = sfsdsdf
      last_number = last_dt.d_index if last_dt
      
      self.d_index = last_number+1
      self.d_number = self.d_prefix+self.d_year.to_s+('%05d' % self.d_index)
      self.save #(:validate => false)
      
     
    end
  end
	def verify(size=16)
		if !self.token
			s = ""
			size.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
			self.token = s
    end
  end
  
  
end
