/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

define([
    'jquery',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/grid/listing',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications'
], function ($, _, listingModel, errorMessagesModel, notifications) {
    'use strict';

    /**
     * Convert form data to JSON
     *
     * @param {Object} form
     * @returns {Object}
     */
    function convertForm(form)
    {
        var data = {},
            j;

        $.map(form.serializeArray(), function (n) {
            const keys = n.name.match(/[a-zA-Z0-9_]+|(?=\[\])/g);

            if (keys.length > 1) {
                let tmp = data,
                    pop = keys.pop();

                for (let i = 0; i < keys.length, j = keys[i]; i++) {
                    tmp[j] = !tmp[j] ? pop === '' ? [] : {} : tmp[j],
                        tmp = tmp[j];
                }

                if (pop === '') {
                    tmp = !Array.isArray(tmp) ? [] : tmp, tmp.push(n.value);
                } else {
                    tmp[pop] = n.value;
                }
            } else {
                data[keys.pop()] = n.value;
            }
        });

        return data;
    }

    /**
     * Process selections data
     *
     * @param {Object} data - Selections data.
     * @param {Object} settings - Form settings (optional).
     * @param {String} defaultStoreId - Default store ID to use if not set in filters.
     * @returns {Object} Processed selections.
     */
    function processSelections(data, settings, defaultStoreId)
    {
        var itemsType = '',
            selections = {};

        _.extend(data.params, settings || {});

        itemsType = data.excludeMode ? 'excluded' : 'selected';

        /** Fixes for select all not actually selecting all */
        if (data && data.excludeMode) {
            data.selected = listingModel.ids().filter(id => !data.excluded.includes(id));
            selections.selected = listingModel.ids().filter(id => !data.excluded.includes(id));
        }

        selections[itemsType] = data[itemsType];

        if (!selections[itemsType].length) {
            selections[itemsType] = false;
        }

        _.extend(selections, data.params || {});

        /* set default store filter */
        if (selections['filters'] && !selections['filters']['store_id']) {
            selections['filters']['store_id'] = defaultStoreId;
        }

        return selections;
    }

    /**
     * Ping API
     *
     * @param {Object} self - Self data.
     * @param {Object} action - Action data.
     * @param {Object} data - Callback data.
     * @param {Function} callback - Callback function.
     * @param {Function} removeNotification - Remove notification function.
     *
     * @returns {Object} Ping data.
     */
    function pingApi(self, action, data, callback, removeNotification)
    {
        $.ajax({
            url: self.pingUrl,
            type: 'GET',
            data: {},
            dataType: 'json',
            async: true,
            showWriteTextAILoader: true,
            success: function (response) {
                if (!response.success) {
                    errorMessagesModel.messages.push(response.message);
                    removeNotification();
                } else {
                    callback(self, action, data);
                }
            }
        });
    }

    return {
        convertForm: convertForm,
        processSelections: processSelections,
        pingApi: pingApi
    };
});
