#include "..\script_component.hpp"

/*
 * Function: dragonfly_db_fnc_subscribe
 * Author: J. Schmidt
 * Edit: 07.15.2024
 * Copyright © 2024 J. Schmidt, All rights reserved
 *
 * Do not edit without permission!
 *
 * This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
 * To view a copy of this license, vist https://creativecommons.org/licenses/by-nc-sa/4.0/ or send a letter to Creative Commons,
 * PO Box 1866, Mountain View, CA 94042
 *
 * [Description]
 * Subscribe to a DragonflyDB channel for real-time updates.
 * Uses CBA event system for message handling.
 *
 * Arguments:
 * 0: STRING - Channel name to subscribe to (default: "")
 * 1: STRING - Event type: "global", "local", "server", or "remote" (default: "global")
 * 2: STRING - CBA event name to trigger when messages are received (default: "")
 * 3: STRING - NetID of target to receive messages (only needed for "remote" event type) (default: nil)
 *
 * Return Value:
 * BOOLEAN - True if successful, false otherwise
 *
 * Examples:
 * ["global_chat", "global", "myChatEvent"] call dragonfly_db_fnc_subscribe
 * ["player_notifications", "remote", "playerNotificationEvent", netId player] call dragonfly_db_fnc_subscribe
 *
 * Public: Yes
 */

params [
    ["_channel", "", [""]],
    ["_eventType", "global", [""]],
    ["_eventName", "", [""]],
    ["_target", nil, [""]]
];

if (_channel isEqualTo "") exitWith {
    diag_log text format ["ArmaDragonflyClient: 'dragonfly_db_fnc_subscribe' Invalid Input for Channel '%1'", _channel];
    false
};

if (!(_eventType in ["global", "local", "server", "remote"])) exitWith {
    diag_log text format ["ArmaDragonflyClient: 'dragonfly_db_fnc_subscribe' Invalid Input for Event Type '%1'", _eventType];
    false
};

if (_eventType isEqualTo "remote" && (isNil "_target" || _target isEqualTo "")) exitWith {
    diag_log text format ["ArmaDragonflyClient: 'dragonfly_db_fnc_subscribe' Invalid Input for Target NetID '%1'", _target];
    false
};

if (_eventName isEqualTo "") exitWith {
    diag_log text format ["ArmaDragonflyClient: 'dragonfly_db_fnc_subscribe' Invalid Input for Event Name '%1'", _eventName];
    false
};

private _args = [_channel, _eventType, _eventName];

if (!isNil "_target") then { _args pushBack _target; };

private _formattedArgs = _args apply { if (_x isEqualType "") then { str _x } else { _x } };
private _extensionArgs = _formattedArgs joinString ",";
private _result = "ArmaDragonflyClient" callExtension ["subscribe", [_extensionArgs]];

diag_log text format ["ArmaDragonflyClient: 'dragonfly_db_fnc_subscribe' Subscribed to channel '%1' with event type '%2' and event name '%3'", _channel, _eventType, _eventName];

true