#include "..\script_component.hpp"

/*
 * Function: forge_client_org_fnc_invite
 * Author: J. Schmidt
 * 
 * Description:
 * Sends an invitation to a player to join an organization
 *
 * Arguments:
 * 0: _uid - Player UID <STRING>
 * 1: _name - Organization name <STRING>
 * 2: _targetUID - Target player's UID <STRING>
 * 3: _targetName - Target player's name <STRING>
 *
 * Return Value:
 * Success <BOOL>
 */

params [["_uid", "", [""]], ["_name", "", [""]], ["_targetUID", "", [""]], ["_targetName", "", [""]]];

if (_uid == "" || _name == "" || _targetUID == "" || _targetName == "") exitWith { TRACE_3("Invalid parameters for organization invitation",_uid,_name,_targetUID); false };

private _store = call FUNC(verifyOrgStore);
private _key = format ["%1_%2", _uid, _name];
private _org = _store call ["getByKey", [_key]];

private _timestamp = systemTimeUTC apply { if (_x < 10) then { "0" + str _x } else { str _x }};
private _dateTime = format ["%1-%2-%3_%4:%5:%6.%7", _timestamp#0, _timestamp#1, _timestamp#2, _timestamp#3, _timestamp#4, _timestamp#5, _timestamp#6];

if (isNil "_org") exitWith { TRACE_1("Organization not found",_key); false };

private _invites = _org get "invites";
private _logs = _org get "logs";

private _invite = createHashMapFromArray [
    ["uid", _targetUID],
    ["name", _targetName],
    ["timestamp", _dateTime],
    ["status", "pending"]
];

_invites set [_targetUID, _invite];
_org set ["invites", _invites];

_logs pushBack [_dateTime, "INVITE", _targetName, _targetUID];
_org set ["logs", _logs];

_store call ["post", [_uid, _name]];

[_targetUID, _uid, _name, _dateTime] spawn {
    params ["_targetUID", "_ownerUID", "_orgName", "_timestamp"];

    if (isRemoteExecuted && remoteExecutedOwner != 2) exitWith {};

    private _target = [_targetUID] call BIS_fnc_getUnitByUID;

    if !(isNull _target) then {
        private _orgInvites = GETVAR(profileNamespace,FORGE_ORG_INVITES,createHashMap);
        private _inviteKey = format ["%1_%2", _ownerUID, _orgName];
        
        _orgInvites set [_inviteKey, createHashMapFromArray [
            ["orgName", _orgName],
            ["ownerUID", _ownerUID],
            ["timestamp", _timestamp],
            ["status", "pending"]
        ]];

        SETVAR(profileNamespace,FORGE_ORG_INVITES,_orgInvites);
        saveProfileNamespace;

        [format ["You have been invited to join %1", _orgName]] remoteExec ["hint", _target];
    };
};

true