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

define([
    'jquery',
    'Magento_Ui/js/form/components/button',
    'Magento_Ui/js/block-loader',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages'
], function ($, Button, blockLoader, errorMessagesModel) {
    'use strict';

    try {
        blockLoader();
    } catch (e) {
        console.log("blockloader failed", e);
    }

    return Button.extend({
        defaults: {
            saveUrl: '',
            enableComparisonPopup: true,
            entityType: 'product',
            isLoading: false,
            originalValue: true
        },

        /** @inheritdoc */
        initObservable: function () {
            return this._super()
                .observe([
                    'enableComparisonPopup',
                    'entityType',
                    'saveUrl',
                    'isLoading',
                    'originalValue'
                ]);
        },

        /**
         * Reset grid settings.
         */
        reset: function () {
            this.enableComparisonPopup(this.originalValue());
        },

        /**
         * Save grid settings.
         */
        save: function () {
            var self = this,
                data = {
                    enable_comparison_popup: this.enableComparisonPopup(),
                    entity_type: '',
                    scope: 'grid'
            };

            errorMessagesModel.messages([]);

            self.isLoading(true);

            $.ajax({
                url: this.saveUrl(),
                data: data,
                type: 'post',
                dataType: 'json'
            }).done(function (response) {
                if (!response.success) {
                    errorMessagesModel.messages.push(response.message);
                } else {
                    window.location.reload();
                }
            }).always(function () {
                self.isLoading(false);
            });
        }
    });
});
