#include "..\script_component.hpp"

/*
 * Function: forge_client_db_fnc_saveGameState
 * Author: J. Schmidt
 * 
 * Description:
 * Collects and saves the current game state to mission namespace
 *
 * Arguments:
 * None
 *
 * Return Value:
 * Success <BOOL>
 */

if (isNil "companyFunds") then { companyFunds = 0 };
if (isNil "companyRating") then { companyRating = 0 };
if (isNil "companyGenerals") then { companyGenerals = [] };
if (isNil "companyGarageUnlocks") then { companyGarageUnlocks = [] };
if (isNil EGVAR(arsenal,armory_unlocks)) then { EGVAR(arsenal,armory_unlocks) = [[],[],[],[]] };
if (isNil EGVAR(arsenal,garage_unlocks)) then { EGVAR(arsenal,garage_unlocks) = [[],[],[],[],[],[]] };

private _companyData = createHashMapFromArray [
    ["key", "CompanyState"],
    ["funds", companyFunds],
    ["rating", companyRating],
    ["operations", companyGenerals],
    ["garage_unlocks", companyGarageUnlocks]
];

["company", _companyData, "CompanyState"] call FUNC(saveToMission);

{
    if (alive _x) then {
        private _playerData = createHashMapFromArray [
            ["key", getPlayerUID _x],
            ["armory_unlocks", EGVAR(arsenal,armory_unlocks)],
            ["garage_unlocks", EGVAR(arsenal,garage_unlocks)],
            ["locker", GETVAR(_x,FORGE_Locker,[])],
            ["garage", GETVAR(_x,FORGE_Garage,[])],
            ["cash", GETVAR(_x,FORGE_Cash,0)],
            ["bank", GETVAR(_x,FORGE_Bank,0)],
            ["number", GETVAR(_x,FORGE_Phone_Number,"unknown")],
            ["email", GETVAR(_x,FORGE_Email,"unknown@spearnet.mil")],
            ["paygrade", GETVAR(_x,FORGE_Paygrade,"E1")],
            ["reputation", rating _x],
            ["loadout", getUnitLoadout _x],
            ["holster", GETVAR(_x,FORGE_Holster_Weapon,true)],
            ["position", getPosASLVisual _x],
            ["direction", getDirVisual _x]
        ];
        
        if (isNull objectParent _x) then {
            _playerData set ["currentWeapon", currentMuzzle _x];
            _playerData set ["stance", stance _x];
        };

        ["players", _playerData, getPlayerUID _x] call FUNC(saveToMission);
    };
} forEach playableUnits;

private _vehicles = nearestObjects [player, ["LandVehicle"], 50];
{
    if (alive _x) then {
        private _vehicleData = createHashMapFromArray [
            ["key", netId _x],
            ["class", typeOf _x],
            ["position", getPosATL _x],
            ["direction", getDir _x],
            ["health", damage _x]
        ];

        ["vehicles", _vehicleData, netId _x] call FUNC(saveToMission);
    };
} forEach _vehicles;

true