#include "..\script_component.hpp"

/*
 * File: fnc_initMEconomyStore.sqf
 * Author: IDSolutions
 * Date: 2025-12-20
 * Last Update: 2026-01-03
 * Public: No
 *
 * Description:
 *     No description added yet.
 *
 * Parameter(s):
 *     N/A
 *
 * Returns:
 *     Something [BOOL]
 *
 * Example(s):
 *     [parameter] call forge_x_component_fnc_myFunction
 */

#pragma hemtt ignore_variables ["_self"]
GVAR(MEconomyStore) = createHashMapObject [[
    ["#type", "IMedEconomy"],
    ["#create", {
        _self set ["mSpawns", createHashMap];

        GVAR(occupancyTriggers) = [];
        ["INFO", "Medical Store Initialized!", nil, nil] call EFUNC(common,log);
    }],
    ["init", {
        private _mSpawns = (_self get "mSpawns");
        private _prefix = "med_spawn";

        for "_i" from 0 to 10 do {
            private _var = if (_i == 0) then { _prefix } else { format ["%1_%2", _prefix, _i] };
            private _obj = missionNamespace getVariable [_var, objNull];

            if (!isNull _obj) then {
                _mSpawns set [_var, [_obj, (getPos _obj)]];
            };
        };

        if (_mSpawns isEqualTo createHashMap) then {
            ["WARNING", "No medical spawns found in the world.", nil, nil] call EFUNC(common,log);
        } else {
            {
                _y params ["_obj", "_pos"];
                private _trigger = createTrigger ["EmptyDetector", _pos];

                _trigger setVariable ["isOccupied", false, true];
                _trigger setVariable ["linkedObject", _obj, true];
                _trigger setTriggerArea [5, 5, 0, true, 5];
                _trigger setTriggerActivation ["ANYPLAYER", "PRESENT", true];
                _trigger setTriggerStatements [
                    "{ (_x isKindOf 'CAManBase') && _x distance thisTrigger < 0.5 } count thisList > 0",
                    "thisTrigger setVariable ['isOccupied', true, true];",
                    "thisTrigger setVariable ['isOccupied', false, true];"
                ];

                GVAR(occupancyTriggers) pushBack _trigger;
            } forEach _mSpawns;
        };
    }],
    ["onHealed", {
        params [["_unit", objNull, [objNull]]];

        if (isNull _unit) exitWith { ["WARNING", format ["Invalid unit provided: %1", (name _unit)], nil, nil] call EFUNC(common,log); };

        private _uid = getPlayerUID _unit;
        private _account = EGVAR(bank,BankRegistry) get _uid;

        if (isNil "_account") exitWith { ["ERROR", format ["No account found for %1. UID: %2", (name _unit), _uid], nil, nil] call EFUNC(common,log); };

        private _bank = _account get "bank";
        private _cash = _account get "cash";

        private _healCost = 100;
        private _newBalance = 0;

        if (_bank < _healCost && _cash < _healCost) exitWith {
            [CRPC(notifications,recieveNotification), ["danger", "Insufficient Funds", format ["Insufficient funds for %1. Bank: %2, Cash: %3, Required: %4", (name _unit), _bank, _cash, _healCost]], _unit] call CFUNC(targetEvent);
        };

        if (_bank >= _healCost) then {
            _newBalance = _bank - _healCost;
            _account set ["bank", _newBalance];
        } else {
            _newBalance = _cash - _healCost;
            _account set ["cash", _newBalance];
        };

        [CRPC(actor,onActorHealed), [], _unit] call CFUNC(targetEvent);
    }],
    ["onRespawn", {
        params [["_unit", objNull, [objNull]], ["_corpse", objNull, [objNull]], ["_uid", "", [""]]];

        private _loadout = [[], [], [], ["U_BG_Guerrilla_6_1", []], [], [], "", "", [], ["", "", "", "", "", ""]];
        private _medSpawn = (GVAR(occupancyTriggers) select { !(GETVAR(_x,isOccupied,false)) }) param [0, objNull];
        private _medSpawnObj = _medSpawn getVariable ["linkedObject", objNull];
        private _medSpawnPos = (getPosATL _medSpawnObj) vectorAdd [0.05, -0.125, 0.45];
        private _medSpawnDir = getDir _medSpawnObj;

        deleteVehicle _corpse;

        private _player = [_uid] call EFUNC(common,getPlayer);
        [CRPC(actor,onActorRespawn), [_loadout, _medSpawnPos, _medSpawnDir], _player] call CFUNC(targetEvent);
    }],
    ["onKilled", {
        params [["_unit", objNull, [objNull]]];

        private _unitPos = getPosATL _unit;
        private _bodyBag = createVehicle ["forge_bodyBag", _unitPos, [], 0, "NONE"];

        _self call ["saveWeapons", [_unit]];
        _self call ["moveInventory", [_unit, _bodyBag]];
    }],
    ["saveWeapons", {
        params [["_unit", objNull, [objNull]]];

        private _droppedWeapons = [];
        private _droppedItems = [];

        _droppedWeapons pushBack (primaryWeapon _unit);
        _droppedItems append (primaryWeaponItems _unit);
        _droppedItems append (primaryWeaponMagazine _unit);
        _droppedWeapons pushBack (secondaryWeapon _unit);
        _droppedItems append (secondaryWeaponItems _unit);
        _droppedItems append (secondaryWeaponMagazine _unit);

        if (isPlayer _unit) then { _droppedItems pushBack (goggles _unit); };
        if (currentWeapon _unit isEqualTo handgunWeapon _unit) then {
            _droppedWeapons pushBack (handgunWeapon _unit);
            _droppedItems append (handgunItems _unit);
            _droppedItems append (handgunMagazine _unit);
        };

        _unit setVariable [QGVAR(droppedWeapons), _droppedWeapons, true];
        _unit setVariable [QGVAR(droppedItems), _droppedItems, true];
    }],
    ["moveInventory", {
        params [["_unit", objNull, [objNull]], ["_bodyBag", objNull, [objNull]]];

        private _items = [];
        private _weapons = [];
        private _backpack = backpack _unit;
        private _nearHolders = _bodyBag nearObjects ["WeaponHolderSimulated", 3];

        _items pushBack (headgear _unit);
        _items pushBack (uniform _unit);
        _items append (uniformItems _unit);
        _items pushBack (vest _unit);
        _items append (vestItems _unit);
        _items append (backpackItems _unit);
        _weapons pushBack (primaryWeapon _unit);
        _items append (primaryWeaponItems _unit);
        _items append (primaryWeaponMagazine _unit);
        _weapons pushBack (secondaryWeapon _unit);
        _items append (secondaryWeaponItems _unit);
        _items append (secondaryWeaponMagazine _unit);
        _weapons pushBack (handgunWeapon _unit);
        _items append (handgunItems _unit);
        _items append (handgunMagazine _unit);
        _weapons append (_unit getVariable [QGVAR(droppedWeapons), []]);
        _items append (_unit getVariable [QGVAR(droppedItems), []]);
        _items append (assignedItems _unit);
        _items pushBack (_unit call CFUNC(binocularMagazine));

        if !((goggles _unit ) in (_unit getVariable [QGVAR(droppedItems), []])) then { _items pushBack (goggles _unit); };

        _items = _items select { _x isNotEqualTo "" };
        _weapons = _weapons select { _x isNotEqualTo "" };

        { _bodyBag addItemCargoGlobal [_x, 1] } forEach _items;

        {
            private _weaponNonPresent = [_x] call CFUNC(getNonPresetClass);
            if (_weaponNonPresent == "") then { _weaponNonPresent = _x; };
            _bodyBag addWeaponCargoGlobal [_weaponNonPresent, 1];
        } forEach _weapons;

        if (_backpack isNotEqualTo "") then {
            private _backpackNonPresent = [_backpack, "CfgVehicles"] call CFUNC(getNonPresetClass);
            if (_backpackNonPresent == "") then { _backpackNonPresent = _backpack; };
            _bodyBag addItemCargoGlobal [_backpackNonPresent, 1];
        };

        {
            private _holderWeapons = ((getWeaponCargo _x) select 0) select { _x in _weapons };
            if (_holderWeapons isNotEqualTo []) then { deleteVehicle _x; };
        } forEach _nearHolders;
    }]
]];

SETMVAR(FORGE_MEconomyStore,GVAR(MEconomyStore));
GVAR(MEconomyStore)
