#include "..\script_component.hpp"

/*
 * Function: forge_client_org_fnc_join
 * Author: J. Schmidt
 * 
 * Description:
 * Adds a player to an organization, either as a new member or the owner
 *
 * 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>
 * 4: _targetRank - Player's rank in organization (default: "member") <STRING>
 *
 * Return Value:
 * Success <BOOL>
 */

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

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

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

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 _members = _org get "members";

{
    private _checkOrg = _x;
    private _checkMembers = _checkOrg get "members";
    if (!isNil { _checkMembers get _targetUID }) exitWith {
        _playerAlreadyInOrg = true;
    };
} forEach (_store call ["get", []]);

if (_playerAlreadyInOrg) exitWith { TRACE_2("Player already in an organization",_targetUID,_targetName); false };

private _member = createHashMapFromArray [
    ["uid", _targetUID],
    ["name", _targetName],
    ["rank", _targetRank],
    ["joinDate", _dateTime]
];

if (_targetRank == "owner") then {
    _members set [_targetUID, _member];
    _org set ["members", _members];

    _store call ["post", [_uid, _name]];
    true
} else {
    if !(isNil { _invites get _targetUID }) then {
        _invites deleteAt _targetUID;
        _members set [_targetUID, _member];

        _org set ["members", _members];
        _org set ["invites", _invites];

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

        private _inviteKey = format ["%1_%2", _uid, _name];
        private _orgInvites = GETVAR(profileNamespace,FORGE_ORG_INVITES,createHashMap);

        _orgInvites deleteAt _inviteKey;
        SETVAR(profileNamespace,FORGE_ORG_INVITES,_orgInvites);
        saveProfileNamespace;

        _store call ["post", [_uid, _name]];
        true
    } else {
        TRACE_2("Player not invited to this organization",_targetUID,_name);
        false
    };
};