#include "..\script_component.hpp"

params [["_player", objNull, [objNull]]];

if (!isServer) exitWith {
	[
		LEVEL_ERROR,
		QUOTE(COMPONENT),
		"ATTEMPTED RUN ON CLIENT",
		[
			["player", _player]
		]
	] call EFUNC(common,log);
};
if (isNull _player) exitWith {
	[
		LEVEL_ERROR,
		QUOTE(COMPONENT),
		"NULL PARAMETERS",
		[
			["player", _player]
		]
	] call EFUNC(common,log);
};

// get entries for this player from queue
private _unitArrs = GVAR(reinsertionQueue) select {_x#0 isEqualTo _player};
// if player not in queue, skip
if (count _unitArrs isEqualTo 0) exitWith {};

private _maxRangeToReady = missionNamespace getVariable [QGVAR(setting_maxRangeToReady), 400];

// remove player from queue
GVAR(reinsertionQueue) = GVAR(reinsertionQueue) - _unitArrs;
// broadcast new list to all machines
publicVariable QGVAR(reinsertionQueue);

// sort _unitArrs by time in queue, descending, to get longest wait (if for some reason there's a duplicate)
[_unitArrs, [], {
	_x#2
}, "DESCEND"] call BIS_fnc_sortBy;

// get first entry (longest wait)
(_unitArrs#0) params ["_player", "_base", "_timeFiled"]; // _unitArr = [unit, base, timeInQueue]
// get the closest base to the player
private _nearestBase = [_player] call EFUNC(common,getNearestBase);
// log to rpt
[
	LEVEL_INFO,
	QUOTE(COMPONENT),
	"PLAYER RESCINDED REQUEST",
	[_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);