#include "..\script_component.hpp"

/*
 * Function: forge_client_org_fnc_leave
 * Author: J. Schmidt
 * 
 * Description:
 * Removes a player from an organization
 *
 * Arguments:
 * 0: _ownerUID - Organization owner's UID <STRING>
 * 1: _orgName - Organization name <STRING>
 * 2: _playerUID - Player's UID who is leaving <STRING>
 * 3: _playerName - Player's name who is leaving <STRING>
 *
 * Return Value:
 * Success <BOOL>
 */

params [["_ownerUID", "", [""]], ["_orgName", "", [""]], ["_playerUID", "", [""]], ["_playerName", "", [""]]];

if (_ownerUID == "" || _orgName == "" || _playerUID == "" || _playerName == "") exitWith { TRACE_4("Invalid parameters for leaving organization",_ownerUID,_orgName,_playerUID,_playerName); false };

private _store = call FUNC(verifyOrgStore);
private _key = format ["%1_%2", _ownerUID, _orgName];
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 _members = _org get "members";
private _logs = _org get "logs";

if (isNil { _members get _playerUID }) exitWith { TRACE_2("Player not in this organization",_playerUID,_orgName); false };

private _memberData = _members get _playerUID;

if (_memberData get "rank" == "owner") exitWith { TRACE_2("Owner cannot leave organization, must transfer ownership first",_playerUID,_orgName); false };

_logs pushBack [_dateTime, "LEAVE", _playerName, _playerUID];
_org set ["logs", _logs];

_members deleteAt _playerUID;
_org set ["members", _members];

_store call ["post", [_ownerUID, _orgName]];

true