#include "..\script_component.hpp"

/*
 * Function: forge_client_org_fnc_removeAsset
 * Author: J. Schmidt
 * 
 * Description:
 * Removes an asset from an organization's inventory
 *
 * Arguments:
 * 0: _uid - Player UID <STRING>
 * 1: _name - Organization name <STRING>
 * 2: _assetType - Type of asset (vehicle, building, etc.) <STRING>
 * 3: _assetId - Unique identifier of the asset <STRING>
 *
 * Return Value:
 * Updated assets collection <HASHMAP>
 */

params [["_uid", "", [""]], ["_name", "", [""]], ["_assetType", "", [""]], ["_assetId", "", [""]]];

if (_uid isEqualTo "" || _name isEqualTo "" || _assetType isEqualTo "" || _assetId isEqualTo "") exitWith { TRACE_4("Invalid parameters for removing asset",_uid,_name,_assetType,_assetId); createHashMap };

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",_name); createHashMap };

private _assets = _org get "assets";
private _logs = _org get "logs";
private _typeAssets = _assets getOrDefault [_assetType, []];
private _index = _typeAssets findIf { (_x getOrDefault ["id", ""]) == _assetId };

if (_index != -1) then {
    private _assetToRemove = _typeAssets select _index;
    private _assetName = _assetToRemove getOrDefault ["name", "Unknown Asset"];

    _typeAssets deleteAt _index;

    _logs pushBack [_dateTime, "ASSET_REMOVED", _assetType, _assetName];
    _org set ["logs", _logs];
};

_org set ["assets", _assets];

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

_assets