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

define([
    'jquery',
    'ko',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/grid/popups/keyword-analysis-progress',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/magento/grid/columns/column',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/progress',
    'WriteTextAI_WriteTextAI/js/model/total-credits',
    'mage/translate'
], function (
    $,
    ko,
    notifications,
    keywordAnalysis,
    keywordAnalysisProgressModel,
    referenceProducts,
    Column,
    keywordsProgressModel,
    totalCredits,
    $t
) {
    'use strict';

    return Column.extend({
        defaults: {
            statusRunning: 'Running',
            statusPending: 'Pending'
        },

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

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

            this.hasProAccess = ko.computed(function () {
                return totalCredits.hasProAccess();
            }, this);

            return this;
        },

        /**
         * Open single editor.
         *
         * @param {Object} record
         * @returns {void}
         */
        showEditPage: function (record) {
            var action = {
                provider:
                    'wtai_categories_grid_listing.wtai_categories_grid_listing.categories_columns.actions',
                target: 'applyAction',
                params: ['edit', '${ $.$data.rowIndex }']
            };

            this.applySingleAction(record._rowIndex, action);
        },

        /**
         * Get breadcrumbs.
         *
         * @param {Object} record
         *
         * @returns {string}
         */
        getBreadcrumbs: function (record) {
            if (record.breadcrumbs) {
                return record.breadcrumbs;
            }
        },

        /**
         * Check if keyword analysis is in progress.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        isKeywordAnalysisInProgress: function (record) {
            return ko.computed(function () {
                try {
                    return this.checkIfOptimizing(record);
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Check if keyword analysis failed.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        isKeywordAnalysisFailed: function (record) {
            return ko.computed(function () {
                try {
                    if (!this.hasProAccess()) {
                        return false;
                    }

                    var failedIds = keywordAnalysisProgressModel.status().failedIds || [];
                    var failedInBulk = failedIds.includes(record.entity_id);
                    var failedInSingle = keywordAnalysis.statuses().find(function (status) {
                        return Number(status.storeId) === Number(record.store_id) &&
                            Number(status.recordId) === Number(record.entity_id) &&
                            status.status === 'Failed';
                    });
                    
                    var isOptimizing = this.checkIfOptimizing(record);
                    var keywordAnalysisStatusFailed = record['optimization_status'] === 'Failed' &&
                        isOptimizing === undefined;
                    
                    return failedInBulk || failedInSingle || keywordAnalysisStatusFailed;
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Get analysis status.
         *
         * @param {Object} record
         * @returns {String}
         */
        getAnalysisStatus: function (record) {
            var isQueued = notifications.statuses().some((status) => {
                if (!status) {
                    return false;
                }

                var subType = Number(status.subType);
                if (!(subType === 2 || subType === 1)) {
                    return false;
                }

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

                return (status.status === this.statusRunning &&
                    (status.queuedIds || []).indexOf(record.entity_id) !== -1) ||
                    (status.status === this.statusPending &&
                    (status.queuedIds || []).indexOf(record.entity_id) !== -1);
            }, this);

            var isProductOptimizationQueued = record.optimization_status === 'Pending';
            if (isQueued || isProductOptimizationQueued) {
                return $t('Queued for keyword analysis');
            }
            return $t('Keyword analysis currently in progress');
        },

        /**
         * Check if keyword analysis is optimizing.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        checkIfOptimizing: function (record) {
            var isQueued = notifications.statuses().some((status) => {
                if (!status) {
                    return false;
                }

                var subType = Number(status.subType);
                if (!(subType === 2 || subType === 1)) {
                    return false;
                }

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

                return (status.status === this.statusRunning &&
                    ((status.runningIds || []).indexOf(record.entity_id) !== -1 ||
                        (status.queuedIds || []).indexOf(record.entity_id) !== -1)) ||
                    (status.status === this.statusPending &&
                    (status.queuedIds || []).indexOf(record.entity_id) !== -1);
            }, this);
            var isCategoryOptimizing = keywordAnalysis.statuses().find(function (status) {
                return Number(status.storeId) === Number(referenceProducts.storeId()) &&
                    Number(status.recordId) === Number(record.entity_id) &&
                    status.status === 'Running' &&
                    status.recordType === 'Category';
            });
            var isBulkOptimizing = keywordAnalysisProgressModel.status().status === this.statusRunning &&
                keywordAnalysisProgressModel.status().queuedIds.includes(record.entity_id);

            var isCategoryOptimizationDataRunning = record.optimization_status === 'InProgress';
            var isCategoryOptimizationDataQueued = record.optimization_status === 'Pending';
            
            return isBulkOptimizing || isCategoryOptimizing || isCategoryOptimizationDataRunning ||
                isCategoryOptimizationDataQueued || isQueued;
        }
    });
});
