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

define([
    'Magento_Ui/js/grid/provider',
    'WriteTextAI_WriteTextAI/js/utils/grid/filters',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/model/grid/bulk-actions'
], function (
    Provider,
    filtersUtils,
    categoryEditData,
    productEditData,
    bulkActionsData
) {
    'use strict';

    return Provider.extend({
        defaults: {
            isLoading: false,
            currentRequest: null,
            pendingRequests: [],
            isEditPageOpen: false,
            hasPendingReload: false,
            pendingReloadOptions: null
        },


        /**
         * @inheritdoc
         */
        initialize: function () {
            this._super();

            categoryEditData.opened.subscribe(function (opened) {
                this.isEditPageOpen = opened;
                if (opened) {
                    /** Abort all pending requests when category edit page opens */
                    this.abortAllPendingRequests();
                }
            }, this);

            productEditData.opened.subscribe(function (opened) {
                this.isEditPageOpen = opened;
                if (opened) {
                    /** Abort all pending requests when product edit page opens */
                    this.abortAllPendingRequests();
                }
            }, this);

            /** Listen for tab visibility changes */
            this.initTabVisibilityListener();
        },

        /**
         * @inheritdoc
         */
        reload: function (options) {
            var custom,
                showLoader,
                debounce,
                request;

            options = options || {};

            custom =
                typeof options.custom !== 'undefined'
                    ? options.custom
                    : false;
            showLoader =
                typeof options.showLoader !== 'undefined'
                    ? options.showLoader
                    : true;
            debounce =
                typeof options.debounce !== 'undefined'
                    ? options.debounce
                    : false;

            /** Prevent reload when edit page is open */
            if (this.isEditPageOpen) {
                return;
            }

            /** Prevent reload when tab is not visible, but store options for single reload later */
            if (document.hidden) {
                this.hasPendingReload = true;
                this.pendingReloadOptions = options;
                return;
            }

            /** Prevent reload if debounce is enabled and grid is already loading */
            if (debounce && this.isLoading) {
                return;
            }

            /** Allow parallel requests - do not abort previous request */
            /**
             * if (this.currentRequest) {
             *    this.currentRequest.abort();
             * }
             */

            this.isLoading = true;
            bulkActionsData.disableBulkSelect(true);
            bulkActionsData.isLoading(true);
            /** showLoader = true; */

            if (this.params.filters) {
                filtersUtils.resetTargetObject(this.params.filters, this);
                filtersUtils.addDefaultWtaiFilters(this.params.filters, this, this.params.namespace === 'wtai_categories_grid_listing');
                
                if (this.params.filters['writetextai_status']) {
                    filtersUtils.processCustomUrlFilters(this.params.filters['writetextai_status'], this);
                }
                
                filtersUtils.processRecordIdsFilter(this.params.filters, this);
                filtersUtils.processRequestIdFilter(this.params.filters, this);
            }
            
            request = this.storage().getData(this.params, options);
            this.currentRequest = request;
            /** Track this request in pending requests array */
            this.pendingRequests.push(request);

            

            if (custom) {
                if (showLoader) {
                    this.trigger('reload');
                }
            } else {
                this.trigger('reload');
            }

            request.done(this.onReload.bind(this)).fail(this.onError.bind(this));

            return request;
        },

        /**
         * @inheritdoc
         */
        onReload: function (data) {
            this._super(data);

            this.isLoading = false;
            /** Remove completed request from pending requests */
            var index = this.pendingRequests.indexOf(this.currentRequest);
            if (index > -1) {
                this.pendingRequests.splice(index, 1);
            }
            this.currentRequest = null;
            /** Clear pending reload flag and options after successful reload */
            this.hasPendingReload = false;
            this.pendingReloadOptions = null;
            bulkActionsData.disableBulkSelect(false);
            bulkActionsData.isLoading(false);
        },

        /**
         * @inheritdoc
         */
        onError: function (xhr) {
            /** Remove failed request from pending requests */
            var index = this.pendingRequests.indexOf(this.currentRequest);
            if (index > -1) {
                this.pendingRequests.splice(index, 1);
            }
            this.currentRequest = null;
            
            /** Call parent onError */
            this._super(xhr);
        },

        /**
         * Abort all pending requests
         */
        abortAllPendingRequests: function () {
            var i;
            /** Abort all pending requests */
            for (i = 0; i < this.pendingRequests.length; i++) {
                if (this.pendingRequests[i] && this.pendingRequests[i].abort) {
                    this.pendingRequests[i].abort();
                }
            }
            /** Clear the pending requests array */
            this.pendingRequests = [];
            this.currentRequest = null;
            this.isLoading = false;
        },

        /**
         * Initialize tab visibility listener
         */
        initTabVisibilityListener: function () {
            var self = this;
            
            document.addEventListener('visibilitychange', function () {
                /** Execute single reload when tab becomes visible if any were pending */
                if (!document.hidden && self.hasPendingReload) {
                    self.hasPendingReload = false;
                    var options = self.pendingReloadOptions;
                    self.pendingReloadOptions = null;
                    /** Execute single reload with stored options */
                    self.reload(options);
                }
            });
        },

        /**
         * Get parameter by name
         *
         * @param {String} name
         *
         * @returns {String}
         */
        getParameterValueByName: function (name) {
            var url = new URL(window.location.href),
                searchParams = new URLSearchParams(url.search),
                value = searchParams.get(name);

            return value ? value : '';
        }
    });
});
