#include "..\script_component.hpp"

if (!isServer) exitWith {};

// if at least 1 player in the queue has been waiting longer than the configured timeout, notify all players
private _timeout = missionNamespace getVariable [QGVAR(setting_maxWait), 60*20]; // default 20 minutes
private _timeoutPlayers = GVAR(reinsertionQueue) select {
	_x params ["_player", "_base", "_timeFiled"];
	alive (_player) &&
	(diag_tickTime - (_timeFiled)) > _timeout
};
if (count _timeoutPlayers > 0) then {
	// GLOBAL CBA NOTIFY
	private _playerLines = [["Players are still waiting for Re-insert!", 1.2, [1, 0.64, 0, 1]]];
	private _maxRangeToReady = missionNamespace getVariable [QGVAR(setting_maxRangeToReady), 400];

	// get base objects from queue
	private _basesWithPeople = (missionNamespace getVariable [QGVAR(reinsertionQueue), []]) apply {_x#1};
	// get unique base objects
	private _basesWithPeople = _basesWithPeople arrayIntersect _basesWithPeople;

	{
		private _thisBase = _x;

		// Add line for base name
		_playerLines pushBack ([[_thisBase] call EFUNC(common,getNameOfBase), 1, [0,1,0,1]]);

		// Get players under this base
		private _thisBasePlayers = _timeoutPlayers select {_x#1 isEqualTo _thisBase};
		// sort _timeoutPlayers by time in queue, descending
		_thisBasePlayers = [_thisBasePlayers, [], {
			_x params ["_player", "_base", "_timeFiled"];
			_timeFiled;
		}, "DESCEND"] call BIS_fnc_sortBy;


		{ // for each player under this base, add a line
			_x params ["_player", "_base", "_timeFiled"];
			// get the closest base to the player
			private _nearestBase = [_player] call EFUNC(common,getNearestBase);

			// add player to array of players under bases
			_playerLines pushBack ([format [
				"%1: %2 [%3]",
				groupID (group (_player)),
				name _player,
				[diag_tickTime - (_timeFiled), "MM:SS"] call BIS_fnc_secondsToString
			], 0.8, [0.8, 0.8, 0.8, 1]]);

			// log to rpt
			[
				LEVEL_WARNING,
				QUOTE(COMPONENT),
				"PLAYER WAITING OVER TIMEOUT",
				[_player, [
					["filedAtBase", [_base] call EFUNC(common,getNameOfBase)],
					["filedAtBaseDistance", _player distance _base],
					["closestBase", [_nearestBase] call EFUNC(common,getNameOfBase)],
					["closestBaseDistance", _player distance _nearestBase],
					["maxDistanceSetting", _maxRangeToReady],
					["inQueueDuration", diag_tickTime - _timeFiled]
				]] call EFUNC(common,addPlayerInfoToArray)
			] call EFUNC(common,log);
		} forEach _thisBasePlayers;
	} forEach _basesWithPeople;

	// SEND NOTIFY
	_playerLines remoteExec ["CBA_fnc_notify", [0, -2] select isDedicated];
	// RESET NOTIFICATION TIMER
	GVAR(overTimeoutLastNotificationTime) = diag_tickTime;
};