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

define([
    'underscore',
    'ko',
    'Magento_Ui/js/grid/listing',
    'WriteTextAI_WriteTextAI/js/grid/reload',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/grid/bulk-actions',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/currently-generating'
], function (
    _,
    ko,
    Listing,
    reloadGrid,
    signalRModel,
    keywordAnalysis,
    bulkActionsData,
    currentlyGeneratingModel
) {
    'use strict';

    return Listing.extend({
        defaults: {
            gridName: 'wtai_categories_grid_listing.wtai_categories_grid_listing_data_source',
            rowsDisabled: []
        },

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

            this.initObservableRowsDisabled();
        },

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

            this.isGridLoading = ko.computed(function () {
                return bulkActionsData.isLoading();
            }, this);

            return this;
        },

        /**
         * Initialize observables for disabling of rows.
         */
        initObservableRowsDisabled: function () {
            var observable = ko.getObservable(this, 'rows');

            observable.subscribe(function (rows) {
                _.each(
                    rows,
                    function (row) {
                        this.rowsDisabled[row.entity_id] = ko.observable(false);
                        this.rowsDisabled[row.entity_id].subscribe(
                            function (value) {
                                if (value) {
                                    /* this.gridReload(); */
                                }
                            },
                            this,
                            'beforeChange'
                        );
                    },
                    this
                );
            }, this);
        },

        /**
         * Reload grid.
         */
        gridReload: function () {
            var showLoader = false,
                debounce = true;

            reloadGrid.reloadUIComponent(this.gridName, showLoader, debounce);
        },

        /**
         * Check if row is disabled.
         *
         * @param {Object} row
         * @returns {Boolean}
         */
        isRowDisabled: function (row) {
            return ko.computed(function () {
                try {
                    var isOtherUserSingleGenerating = signalRModel.singleGeneratingStatuses().some(function (status) {
                        return status.recordId == row.entity_id &&
                               status.storeId == row.store_id &&
                               status.generationType == 'Category' &&
                               !status.stop;
                    });

                    this.rowsDisabled[row.entity_id](isOtherUserSingleGenerating);
                    var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
                    var categoryIdentifier = 'Category' + '_' + row.entity_id + '_' + row.store_id;
                    var isCurrentlyGenerating = currentlyGeneratingRecordIdentifiers.includes(categoryIdentifier);
                    var isCategoryOptimizationDataRunning = row.optimization_status === 'InProgress';
                    var isCategoryOptimizationDataQueued = row.optimization_status === 'Pending';

                    return isOtherUserSingleGenerating || isCurrentlyGenerating || isCategoryOptimizationDataRunning
                        || isCategoryOptimizationDataQueued;
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Check if row is optimizing.
         *
         * @param {Object} row
         * @returns {Boolean}
         */
        isRowOptimizing: function (row) {
            return ko.computed(function () {
                try {
                    var status = keywordAnalysis.statuses().find(function (status) {
                        return Number(status.storeId) === Number(row.store_id)
                        && status.recordId === row.entity_id
                        && status.status === 'Running'
                        && status.recordType === 'Category';
                    });
    
                    if (status) {
                        return true;
                    }

                    return false;
                } catch (error) {
                    return false;
                }
            }, this);
        }
    });
});
