local PickupItemSystem = inherited("PickupItemSystem", SystemMap)

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

function PickupItemSystem:wants(ent)
	return ent.aspects.pickup_items
end

function PickupItemSystem:ent_added(ent)
end

function PickupItemSystem:ent_removed(ent)
end

function PickupItemSystem:step(dt)
	local world = self.world
	for ent, _ in pairs(self.ents) do	
		local pickups = ent.desired_pickups
		for pickup, _ in pairs(pickups) do
			local dist = math.distance(ent.x, ent.y, pickup.x, pickup.y)
			local force_range = ent.pickup_pull_range
			if dist <= ent.pickup_range then
				--PICKUP
				local item = pickup.item
				local inventory = ent.inventory
				local ok, ejected_item = inventory:add_item(item)
				if ok then
					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(-pickup.dx*math.randomGaussian()*0.25,-pickup.dy*math.randomGaussian()*0.25,125 + math.random()*100)
						world.universe:add_ent(eject)
					end
					world:remove_ent(pickup)
					if ent.inventory_changed then
						ent:inventory_changed()
					end
				else					
				end

				ent:remove_desired_pickup(pickup)
			elseif dist <= force_range then
				local d_x, d_y, d_z = ent.x - pickup.x, ent.y - pickup.y, ent.z - pickup.z
				local speed = ent.pickup_pull_speed
				local acc = ent.pickup_pull_acceleration
				local ang = math.angleBetweenPoints(pickup.x, pickup.y, ent.x, ent.y)

				local dx = math.approach(pickup.dx, math.cos(ang)*speed, math.abs(d_x)*acc*dt)
				local dy = math.approach(pickup.dy, math.sin(ang)*speed, math.abs(d_y)*acc*dt)
				local dz = math.approach(pickup.dz, d_z*speed/force_range, math.abs(d_z)*acc*dt)
				pickup:set_speed(dx,dy,dz)
			end
		end
	end	
end

return PickupItemSystem