/**
 * @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'
], function ($, _, listingModel, errorMessagesModel) {
    '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
     *
     * @returns {Object} Ping data.
     */
    function pingApi(self)
    {
        var pingStatus = false;
        
        $('body').loader('show');
        var pingData = $.ajax({
            url: self.pingUrl,
            type: 'GET',
            data: {},
            dataType: 'json',
            async: false,
            showWriteTextAILoader: true,
            success: function (response) {
                if (!response.success) {
                    errorMessagesModel.messages.push(response.message);
                } else {
                    pingStatus = true;
                }
                setTimeout(function () {
                    $('body').loader('hide');
                }, 100);
            },
            error: function (xhr, status, error) {
                setTimeout(function () {
                    $('body').loader('hide');
                }, 100);
            }
        });
        return pingStatus;
    }

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