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

define([
    'underscore',
    'ko',
    'Magento_Ui/js/grid/columns/multiselect',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/model/grid/bulk-actions',
    'WriteTextAI_WriteTextAI/js/model/grid/listing',
    'WriteTextAI_WriteTextAI/js/categories/model/edit'
], function (_, ko, Multiselect, notifications, bulkActionsData, listingModel, editData) {
    'use strict';

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

            var self = this;

            editData.opened.subscribe(function (opened) {
                if (opened) {
                    self.deselectAll();
                }
            });

            this.currentUserEmail = '';
            try {
                listingModel.currentUser.subscribe(function (user) {
                    if (user && user.email) {
                        self.currentUserEmail = String(user.email);
                    }
                });
            } catch (e) {
                // no-op
            }

            this.isDisabled = ko.pureComputed(function () {
                return Boolean(bulkActionsData.getDisableBulkSelect('Category')());
            }, this);

            window.addEventListener('storage', function (event) {
                if (!event || !event.key) {
                    return;
                }

                if (event.key === bulkActionsData.getDeselectStorageKey('Category') && event.newValue) {
                    setTimeout(function () {
                        self._deselectOngoingItems();
                    }, 200);
                    return;
                }

                if (event.key.indexOf('wtai_notifications_state') === 0 && event.newValue) {
                    setTimeout(function () {
                        self._deselectOngoingItems();
                    }, 100);
                }
            });

            notifications.statuses.subscribe(function (statuses) {

                var queuedIds = [];
                statuses.forEach(function (status) {
                    var currentEmail = String(self.currentUserEmail || '');

                    if (currentEmail && status.user && String(status.user) === currentEmail) {
                        return;
                    }
                    if (status && (status.recordType || 'Product') === 'Category' && status.queuedIds) {
                        queuedIds = queuedIds.concat(status.queuedIds);
                    }
                });

                _.each(queuedIds, function (disabledRowId) {
                    self.deselect(disabledRowId);
                });
            });

            return this;
        },

        /**
         * Returns a map of entity IDs currently being processed.
         */
        _getOngoingIds: function () {
            var ongoingIds = {};
            var terminal = ['Cancelled', 'Completed', 'Failed', 'TimedOut'];
            var currentEmail = String(this.currentUserEmail || '');

            (notifications.statuses() || []).forEach(function (status) {
                if (!status || !status.status || terminal.indexOf(status.status) !== -1) {
                    return;
                }

                if ((status.recordType || 'Product') !== 'Category') {
                    return;
                }

                if (currentEmail && status.user && String(status.user) === currentEmail) {
                    return;
                }

                (status.queuedIds || []).forEach(function (id) {
                    ongoingIds[String(id)] = true;
                });
                (status.runningIds || []).forEach(function (id) {
                    ongoingIds[String(id)] = true;
                });
            });

            return ongoingIds;
        },

        /**
         * Deselect individual items that are part of an ongoing bulk action.
         */
        _deselectOngoingItems: function () {
            var ongoingIds = this._getOngoingIds();

            if (Object.keys(ongoingIds).length === 0) {
                return;
            }

            if (this.excludeMode()) {
                var excluded = this.excluded();
                var toExclude = [];

                Object.keys(ongoingIds).forEach(function (id) {
                    if (excluded.indexOf(id) === -1) {
                        toExclude.push(id);
                    }
                });

                if (toExclude.length > 0) {
                    this.excluded(excluded.concat(toExclude));
                }
            } else {
                var selected = this.selected();

                if (!selected || selected.length === 0) {
                    return;
                }

                var toRemove = [];

                selected.forEach(function (id) {
                    if (ongoingIds[String(id)]) {
                        toRemove.push(id);
                    }
                });

                if (toRemove.length > 0) {
                    toRemove.forEach(function (id) {
                        this.selected.remove(id);
                    }, this);
                }
            }
        },

        /**
         * @inheritdoc
         */
        getFieldHandler: function (row) {
            if (this.isDisabled && this.isDisabled()) {
                return function () {
                    return;
                };
            }

            var ongoingIds = this._getOngoingIds();

            if (row && ongoingIds[String(row.entity_id)]) {
                return function () {
                    return;
                };
            }

            return this._super(row);
        },

        /**
         * @inheritdoc
         */
        toggleSelectAll: function () {
            if (this.isDisabled && this.isDisabled()) {
                return;
            }

            var result = this._super();

            this._deselectOngoingItems();

            return result;
        },

        /**
         * @inheritdoc
         */
        selectAll: function () {
            if (this.isDisabled && this.isDisabled()) {
                return;
            }

            var result = this._super();

            this._deselectOngoingItems();

            return result;
        },

        /**
         * @inheritdoc
         */
        deselectAll: function () {
            return this._super();
        },

        /**
         * @inheritdoc
         */
        select: function (index, data, event) {
            if (this.isDisabled && this.isDisabled()) {
                return;
            }

            return this._super(index, data, event);
        },

        /**
         * @inheritdoc
         */
        deselect: function (index, data, event) {
            return this._super(index, data, event);
        }
    });
});
