#include "..\script_component.hpp"

/*
 * Author: IDSolutions
 * Initialize email store for email management
 *
 * Arguments:
 * N/A
 *
 * Return Value:
 * Email Store Object
 *
 * Examples:
 * [] call forge_server_phone_fnc_initEmailStore
 *
 * Public: No
 */

GVAR(EmailStore) = createHashMapObject [[
    ["#type", "IEmailStore"],
    ["#create", {
        GVAR(EmailRegistry) = createHashMap; // uid -> Array of emails
        diag_log "[FORGE:Server:Phone] Email Store Initialized!";
    }],
    ["init", {
        params [["_uid", "", [""]]];

        if (_uid isEqualTo "") exitWith { diag_log "[FORGE:Server:Phone:Email] Empty UID provided to init"; createHashMap };

        // Initialize email registry for player
        GVAR(EmailRegistry) set [_uid, []];

        // Load existing emails from database into registry
        _self call ["loadEmailsFromDatabase", [_uid]];

        diag_log format ["[FORGE:Server:Phone:Email] Emails initialized for %1", _uid];
        true
    }],
    ["loadEmailsFromDatabase", {
        params [["_uid", "", [""]]];

        if (_uid isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Invalid UID provided for email loading";
            false
        };

        try {
            private _emailData = [format ["%1:emails", _uid]] call dragonfly_db_fnc_lrange;

            if (!isNil "_emailData" && { count _emailData > 0 }) then {
                private _emails = [];

                // Parse emails from database format
                {
                    private _email = _self call ["toHashMap", [_x]];
                    _email set ["id", _forEachIndex];
                    _emails pushBack _email;
                } forEach _emailData;

                GVAR(EmailRegistry) set [_uid, _emails];
            };

            diag_log format ["[FORGE:Server:Phone:Email] Loaded emails for %1 into registry", _uid];
            true
        } catch {
            diag_log format ["[FORGE:Server:Phone:Email] Error loading emails from database for %1: %2", _uid, _exception];
            false
        };
    }],
    ["sendEmail", {
        params [["_fromUid", "", [""]], ["_toUid", "", [""]], ["_subject", "", [""]], ["_body", "", [""]]];

        if (_fromUid isEqualTo "" || _toUid isEqualTo "" || _subject isEqualTo "" || _body isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Invalid parameters provided to sendEmail";
            false
        };

        private _timestamp = serverTime;
        private _emailId = format ["%1_%2_%3", _fromUid, _toUid, _timestamp];

        // Create email object
        private _emailObj = createHashMapFromArray [
            ["id", _emailId],
            ["from", _fromUid],
            ["to", _toUid],
            ["subject", _subject],
            ["body", _body],
            ["timestamp", _timestamp],
            ["read", false]
        ];

        // Add to sender's sent emails (optional - can be implemented later)
        // For now, just add to recipient's inbox

        // Add to receiver's email registry
        private _receiverEmails = GVAR(EmailRegistry) getOrDefault [_toUid, []];
        _receiverEmails pushBack _emailObj;
        GVAR(EmailRegistry) set [_toUid, _receiverEmails];

        // Store in database for recipient
        try {
            private _emailArray = _self call ["toArray", [_emailObj]];
            [format ["%1:emails", _toUid], [_emailArray]] call dragonfly_db_fnc_rpush;

            // Optionally store in sender's sent folder (database key could be something like "%1:sent_emails")
            // [format ["%1:sent_emails", _fromUid], [_emailArray]] call dragonfly_db_fnc_rpush;

        } catch {
            diag_log format ["[FORGE:Server:Phone:Email] Error saving email to database: %1", _exception];
        };

        // TODO: Notify recipient

        diag_log format ["[FORGE:Server:Phone:Email] Email sent from %1 to %2: %3", _fromUid, _toUid, _subject];
        true
    }],
    ["getEmails", {
        params [["_uid", "", [""]]];

        if (_uid isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Empty UID provided to getEmails";
            []
        };

        private _emails = GVAR(EmailRegistry) getOrDefault [_uid, []];

        // Sort by timestamp (newest first)
        _emails sort false;

        diag_log format ["[FORGE:Server:Phone:Email] Retrieved %1 emails for %2", count _emails, _uid];
        _emails
    }],
    ["markEmailRead", {
        params [["_uid", "", [""]], ["_emailId", "", [""]]];

        if (_uid isEqualTo "" || _emailId isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Invalid parameters provided to markEmailRead";
            false
        };

        private _emails = GVAR(EmailRegistry) getOrDefault [_uid, []];
        private _found = false;

        // Find the email and mark it as read
        {
            private _email = _x;
            if ((_email get "id") isEqualTo _emailId) then {
                _email set ["read", true];
                _found = true;
            };
        } forEach _emails;

        if (_found) then {
            diag_log format ["[FORGE:Server:Phone:Email] Marked email %1 as read for %2", _emailId, _uid];
            // TODO: Update database to persist read status
        } else {
            diag_log format ["[FORGE:Server:Phone:Email] Email %1 not found for %2", _emailId, _uid];
        };

        _found
    }],
    ["deleteEmail", {
        params [["_uid", "", [""]], ["_emailId", "", [""]]];

        if (_uid isEqualTo "" || _emailId isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Invalid parameters provided to deleteEmail";
            false
        };

        private _emails = GVAR(EmailRegistry) getOrDefault [_uid, []];
        private _found = false;
        private _newEmails = [];

        // Filter out the email to delete
        {
            private _email = _x;
            if ((_email get "id") isNotEqualTo _emailId) then {
                _newEmails pushBack _email;
            } else {
                _found = true;
            };
        } forEach _emails;

        if (_found) then {
            GVAR(EmailRegistry) set [_uid, _newEmails];
            diag_log format ["[FORGE:Server:Phone:Email] Deleted email %1 for %2", _emailId, _uid];
            // TODO: Update database to remove email
        } else {
            diag_log format ["[FORGE:Server:Phone:Email] Email %1 not found for %2", _emailId, _uid];
        };

        _found
    }],
    ["remove", {
        params [["_uid", "", [""]]];

        if (_uid isEqualTo "") exitWith {
            diag_log "[FORGE:Server:Phone:Email] Empty UID provided to remove";
            false
        };

        // Remove from email registry
        GVAR(EmailRegistry) deleteAt _uid;

        diag_log format ["[FORGE:Server:Phone:Email] Removed email data for %1", _uid];
        true
    }],
    ["toArray", {
        params [["_data", createHashMap, [createHashMap]]];

        private _keys = keys _data;
        private _array = [];

        {
            private _key = _x;
            private _value = _data get _key;
            _array pushBack _key;
            _array pushBack _value;
        } forEach _keys;

        _array
    }],
    ["toHashMap", {
        params [["_data", [], [[]]]];

        private _keyValuePairs = [];
        _data = _data select 0;

        for "_i" from 0 to (count _data - 2) step 2 do {
            private _key = _data select _i;
            private _value = _data select (_i + 1);
            _keyValuePairs set [_key, _value];
        };

        private _hashMap = createHashMapFromArray _keyValuePairs;
        _hashMap
    }]
]];

SETMVAR(FORGE_EmailStore,GVAR(EmailStore));
GVAR(EmailStore)
