local ShopKeeperSystem = inherited("ShopKeeperSystem", SystemMap)

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

ShopKeeperSystem.key = "shop_keepers"

function ShopKeeperSystem:wants(ent)
	return ent.aspects.shop_keeper and ent.shop
end

function ShopKeeperSystem:dynamic_wants(ent)
	return ent.aspects.shop_keeper and ent.shop
end

function ShopKeeperSystem:ent_added(ent)		
end

function ShopKeeperSystem:ent_removed(ent)	
	--assert(false)
end

function ShopKeeperSystem:get_shop_keepers_map()
	return self.ents
end

function ShopKeeperSystem:step(dt)
	local world = self.world

	local team_target_system = world:get_system_by_key("team_shop_customers_target")
	if world then
		for ent, _ in pairs(self.ents) do
			--print("JS")
			if ent.shop_scan_delay > 0 then
				ent.shop_scan_delay = ent.shop_scan_delay - dt				
			else
				local team = ent.team
				if team then

					local best_customer = nil
					local best_dist2 = nil	

					for _, trade_team in ipairs(team:get_trading_teams()) do
						local target_map = team_target_system:get_target_map(trade_team)
						if target_map then
							
							local x,y = ent.x,ent.y					
							local radius = ent.radius
							for target, _ in pairs(target_map) do
								local target_radius = target.radius + target.shopping_range
								local threshold2 = (radius+target_radius)^2
								local dist2 = math.distance2(x, y, target.x, target.y)
								--print(dist2, threshold2)
								if dist2 < threshold2 then
									if not best_dist2 or dist2 < best_dist2 then
										if not world.universe:is_line_of_sight_blocked(x,y, target.x, target.y) then
											best_dist2 = dist2
											best_customer = target										
										end
									end
									--HIT
								end
							end
						end
					end

					if best_customer ~= ent.customer then
						ent:set_shop_customer(best_customer)
					end
				end
				ent.shop_scan_delay = ent.shop_scan_delay_max
			end
		end
	end
end

return ShopKeeperSystem