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

define([
    'jquery',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/utils/grid/image-upload',
    'WriteTextAI_WriteTextAI/js/model/grid/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/model/grid/popups/image-upload-progressbar',
    'WriteTextAI_WriteTextAI/js/utils/grid/actions'
], function (
    $,
    _,
    notifications,
    imageUploadUtils,
    gridInvalidImagePopupModel,
    errorMessagesModel,
    imageUploadProgressbarModel,
    actionsUtils
) {
    'use strict';
    
    /**
     * Bulk generate
     *
     * @param {Object} self - Self data.
     * @param {Object} action - Action data.
     * @param {Object} data - Selections data.
     * @param {Object} settings - Form settings.
     *
     * @returns {void}
     */
    function bulkGenerate(self, action, data, settings)
    {
        /*
        var textTypes = [
            'page_title',
            'page_description',
            'product_description',
            'short_product_description',
            'open_graph'
        ];
        var fieldsWithImageUpload = [
            'alt_text',
            'product_description',
            'category_description',
            'short_product_description'
        ];
        var needGalleryUpload = fieldsWithImageUpload.some(
            field => settings.fields.includes(field)
        ),
            needKeywordsOptimization = settings.auto_optimize_keywords,
            needThumbnailUpload = settings.attributes &&
                settings.attributes.includes('thumbnail') &&
                textTypes.some(
                    textType => settings.fields.includes(textType)
                );if (needThumbnailUpload || needGalleryUpload || needKeywordsOptimization) {
            imageUploadProgressbarModel.toCancel(false);
            imageUploadUtils.uploadImages(self, action, data, settings, 'bulkGenerateRequest');
        }*/
        bulkGenerateRequest(self, action, data, settings);
    }

    /**
     * Bulk generate request
     * via POST request.
     *
     * @param {Object} self - Self data.
     * @param {Object} action - Action data.
     * @param {Object} data - Selections data.
     * @param {Object} settings - Form settings.
     *
     * @returns {void}
     */
    function bulkGenerateRequest(self, action, data, settings)
    {
        notifications.addNewGenerateStatus(
            data.selected,
            gridInvalidImagePopupModel.currentUser(),
            data
        );
        notifications.opened(true);

        var selections = actionsUtils.processSelections(data, settings, self.defaultStoreId);

        notifications.currentBulkRequestId(notifications.tempId);
        
        actionsUtils.pingApi(self, action, selections, mainAjaxRequest, removeNotification);
    }

    /**
     * Main ajax request for bulk generate
     * via POST request.
     *
     * @param {Object} self - Self data.
     * @param {Object} action - Action data.
     * @param {Object} selections - Selections data.
     *
     * @returns {void}
     */
    function mainAjaxRequest(self, action, selections)
    {
        $.ajax({
            url: action.url + '?form_key=' + encodeURIComponent(window.FORM_KEY),
            type: 'POST',
            data: JSON.stringify(selections),
            contentType: 'application/json',
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (!response.success) {
                    errorMessagesModel.messages.push(response.message);
                    notifications.statuses.remove(function (status) {
                        return status.id === notifications.tempId;
                    });
                    if (response.unauthorized) {
                        window.location.href = response.login_url;
                    }
                    if (response.reload) {
                        self.gridReload();
                    }
                } else {
                    notifications.updateTempStatusId(response.api_response.requestId, notifications.tempId);
                    console.log('update currentBulkRequestId');
                    notifications.currentBulkRequestId(response.api_response.requestId);
                }
            }
        });
    }

    /**
     * Remove notification
     *
     * @returns {void}
     */
    function removeNotification()
    {
        notifications.statuses.remove(function (status) {
            return status.id === notifications.tempId;
        });
    }

    return {
        bulkGenerate: bulkGenerate,
        bulkGenerateRequest: bulkGenerateRequest,
        mainAjaxRequest: mainAjaxRequest,
        removeNotification: removeNotification
    };
});
