local is_parties_enabled = core.get_modpath("parties")



arena_lib.on_generate_teams("block_league", function(arena, max_curr_amount)
	local lvls = {}
	local sum_team1, sum_team2 = 0, 0

	-- metto in `lvls` solo quell3 non in gruppo
	for pl_name, pl_data in pairs(arena.players) do
		if not pl_data.teamID then
			lvls[#lvls+1] = {name = pl_name, lv = block_league.get_player_level(pl_name)}
		end
	end

	table.sort(lvls, function(a, b) return a.lv > b.lv end)

	-- se c'è gente in gruppo, sommo prima i loro livelli
	if max_curr_amount > 0 then
		for pl_name, pl_data in pairs(arena.players) do
			if pl_data.teamID == 1 then
				sum_team1 = sum_team1 + block_league.get_player_level(pl_name) + 1 -- + 1 perché sennò i lv 0 non hanno peso nel conteggio
			elseif pl_data.teamID == 2 then
				sum_team2 = sum_team2 + block_league.get_player_level(pl_name) + 1
			end
		end
	end

	-- assegno la squadra bilanciando i valori di sum_team1 e sum_team2 il più possibile
	for _, data in ipairs(lvls) do
		if sum_team1 <= sum_team2 and arena.players_amount_per_team[1] < arena.max_players then
			arena.players[data.name].teamID = 1
			arena.players_amount_per_team[1] = arena.players_amount_per_team[1] + 1
			sum_team1 = sum_team1 + data.lv + 1 -- +1 idem come sopra
		else
			arena.players[data.name].teamID = 2
			arena.players_amount_per_team[2] = arena.players_amount_per_team[2] + 1
			sum_team2 = sum_team2 + data.lv + 1
		end
	end

	-- se ci sono 2+ persone in più in una squadra, sposta quella col lv più basso
	-- di là (alquanto raro che ce ne siano 3 o più, non tengo conto di questa casistica
	-- al momento)
	if math.abs(arena.players_amount_per_team[1] - arena.players_amount_per_team[2]) > 1 then
		local team = arena.players_amount_per_team[1] < arena.players_amount_per_team[2] and 2 or 1
		local lowest_lv = {name = "", lv = 99}

		for pl_name, pl_data in pairs(arena.players) do
			if pl_data.teamID == team and (not is_parties_enabled or not parties.is_player_in_party(pl_name)) then
				local p_lv = block_league.get_player_level(pl_name)
				if p_lv < lowest_lv.lv then
					lowest_lv = {name = pl_name, lv = p_lv}
				end
			end
		end

		-- se tutta la squadra in eccesso è in un gruppo (ergo il valore .name non è cambiato), annulla
		if lowest_lv.name == "" then return end

		local new_team = team == 1 and 2 or 1

		arena.players[lowest_lv.name].teamID = new_team
		arena.players_amount_per_team[team] = arena.players_amount_per_team[team] -1
		arena.players_amount_per_team[new_team] = arena.players_amount_per_team[new_team] +1
	end
end)
