local BuyItemSystem = inherited("BuyItemSystem", SystemMap)

function BuyItemSystem:new()
	local ms = instance(self)
	return ms
end

function BuyItemSystem:dynamic_wants(ent)
	return ent.aspects.shop_customer and ent.buy_slot
end

function BuyItemSystem:ent_added(ent)
end

function BuyItemSystem:ent_removed(ent)
end

function BuyItemSystem:step(dt)
	local world = self.world
	for ent, _ in pairs(self.ents) do
		local buy_slot = ent.buy_slot
		if buy_slot then
			local item = buy_slot:get_item()
			local price = buy_slot:get_price()
			local inventory = ent.inventory
			local gold_item = inventory:get_selected_item_of_type("gold")
			if not price or (gold_item and gold_item:get_stack() >= price) then
				local ok, ejected_item = inventory:add_item(item)
				if ok then
					if price then
						gold_item:adjust_stack(-price)
					end
					buy_slot:clear_item()
					if ejected_item then
						local eject = Entity:new("pickup", ent.x, ent.y, ent.z + ent.pickup_z)
						eject:set_item(ejected_item)
						eject:set_speed(math.randomGaussian()*25,math.randomGaussian()*25,125 + math.random()*100)
						world.universe:add_ent(eject)
					end
					ent:set_buy_slot_intent(nil)				
					if ent.inventory_changed then
						ent:inventory_changed()
					end
				else
				end
			end
		end
	end
end

return BuyItemSystem