/*
	Function: milsim_reinsert_fnc_showReinsertQueueNotification

	Description:
		Designed to be remoteExecuted on the server. Will show a CBA notification on the remoteExecutedOwner's screen with the current reinsertion queue and log this occurrence in the server RPT.

	Author: IndigoFox
*/

#include "..\script_component.hpp"

if (not isRemoteExecuted) exitWith {
	diag_log text format ["[milsim] (respawn_reinsertion) SHOW QUEUE NOT REMOTE EXECUTED"];
};
if (not isServer) exitWith {
	diag_log text format ["[milsim] (respawn_reinsertion) SHOW QUEUE NOT RUN ON SERVER"];
};

private _users = allUsers apply {getUserInfo _x} select {count _x > 0};
private _userIndex = _users findIf {_x#1 isEqualTo remoteExecutedOwner};
if (_userIndex isEqualTo -1) exitWith {
	diag_log text format ["[milsim] (respawn_reinsertion) SHOW QUEUE USER NOT FOUND"];
};
private _userObject = _users select _userIndex select 10;
if (isNull _userObject) exitWith {
	diag_log text format ["[milsim] (respawn_reinsertion) SHOW QUEUE USER OBJECT NOT FOUND"];
};

// log to rpt
[
	LEVEL_INFO,
	QUOTE(COMPONENT),
	"SHOW QUEUE REQUESTED",
	[_userObject] call EFUNC(common,addPlayerInfoToArray)
] call EFUNC(common,log);

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

// text array to use in notification
private _par = [["Players Awaiting Reinsert", 1.2, [1,0.64,0,1]]];

if (count _basesWithPeople isEqualTo 0) then {
	_par pushBack ["[QUEUE EMPTY]", 1, [1,1,1,1]];
};

// forEach _basesWithPeople
{
	private _thisBase = _x;
	private _baseName = [_thisBase] call EFUNC(common,getNameOfBase);
	
	// generate player lines for this base
	private _playerLines = _queue select {
		_x#1 isEqualTo _thisBase
	} apply {
		_x params ["_player", "_base", "_timeFiled"];
		[
			format [
				"%1: %2 [%3]",
				groupId (group _player),
				name _player,
				[diag_tickTime - _timeFiled, "MM:SS"] call BIS_fnc_secondsToString
			],
			0.8,
			[1,1,1,1]
		];
	};

	// determine suffix for player count based on count
	private _playerCountText = "";
	switch (count _playerLines) do {
		case 0: {
			_playerCountText = "No players";
		};
		case 1: {
			_playerCountText = "1 player";
		};
		default {
			_playerCountText = format ["%1 players", count _playerLines];
		};
	};
	
	// add base name and player count to notification lines
	_par pushBack [
		format ["Location: %1 (%2)", 
			_baseName, 
			_playerCountText
		],
		1,
		[0,1,0,1]
	];

	// sort by text (first piece of text is group name)
	_playerLines = [
		_playerLines,
		[],
		{_x#0}
	] call BIS_fnc_sortBy;

	// add to notification lines	
	{
		_par pushBack _x;
	} forEach _playerLines;
} forEach _basesWithPeople;

_par remoteExec ["CBA_fnc_notify", remoteExecutedOwner];

true;