class InventoryDefinition < ApplicationRecord

  scope :active, -> {where(:is_active => true)}

  def self.calculate_product_count(saleObj)
    saleObj.sale_items.each do |item|
      found, inventory_definition = find_product_in_inventory(item)
      if found
        check_balance(item,inventory_definition)
      end
    end
  end

  def self.find_product_in_inventory(item)
    product = InventoryDefinition.find_by_item_code(item.item_instance_code)
    if product.nil?
      return false, nil
    else
      return true, product
    end
  end

  def self.check_balance(item,inventory_definition) # item => saleItemOBj
     stock = StockJournal.where('item_code=?', item.item_instance_code).order('created_at desc').take
     unless stock.nil?
       modify_balance(item, stock, inventory_definition)
     else
       StockJournal.add_to_journal(item, 0, "out of stock", inventory_definition)
     end
  end

  def self.modify_balance(item, stock, inventory_definition) #saleitemObj
     if stock.balance.to_i >= item.qty
       puts ">> stock is greater than orde qty"
       StockJournal.add_to_journal(item, stock.balance, "ok", inventory_definition)
     else
       puts " << stock is less than order qty"
       StockJournal.add_to_journal(item, stock.balance, "out of stock", inventory_definition)
     end
  end
end
