----- EXPERIMENTAL FAIR-MAP GENERATION -----

-- generate "num" neutrals fairly given an array of "homes"
function generate_map(homes, num, tolerance, gen_function)
    local map
    if gen_function == nil then map = standard_gen(num) else map = gen_function(num) end
    
    local values = {}
    for i,home in ipairs(homes) do
        values[i] = map_value(home, map)
    end
    local total_value = 0
    for i,value in ipairs(values) do
        total_value = total_value + value
    end
    local average_value = total_value/#values
    local is_fair_map = true
    for i,value in ipairs(values) do
        if value < GLOBAL.min_map_value or math.abs(value/average_value) > tolerance or math.abs(average_value/value) > tolerance then
            is_fair_map = false
        end
    end
    if is_fair_map then return map else return generate_map(homes,num,tolerance*1.01,gen_function) end -- increase tolerance so the game doesn't freeze while trying to find a good map
end   

-- standard map generation function
function standard_gen(num)
    local pad = 50; local sw = GLOBAL.play_sw; local sh = GLOBAL.play_sh
    local map = {}
    for j=1,num do
        map[j] = {position_x = math.random(pad,sw-pad),position_y = math.random(pad,sh-pad),ships_production = math.random(15,100),ships_value = math.random(0,50)}
    end
    return map
end
    
-- how "good" the map is relative to a players' home planet
function map_value(home, map)
    local value = 0
	for i,p in ipairs(map) do
		local arrival_time = distance_to_time(home:distance(p))
		-- Heuristic#1: represents the number of net ships taking this planet would yield GLOBAL.horizon seconds in the future	
		if time_to_break_even(p, arrival_time) < GLOBAL.horizon then
		    local net_ships = -p.ships_value + (GLOBAL.horizon - arrival_time) * p.ships_production / 50.0
		    value = value + net_ships
		end
    end
    return value
end
		    
-- if a user were to attack this planet, how long would it take
-- for the user to break even on ship investment?
function time_to_break_even(p, time_overhead)
	return p.ships_value / (p.ships_production / 50.0) + time_overhead
end		    

-- "Time-distance" for a length distance
function distance_to_time(distance)
	return distance/40
end