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

define([
    'jquery',
    'ko',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    '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/model/total-credits',
    'Magento_Ui/js/grid/columns/column',
    'mage/translate'
], function (
    $,
    ko,
    textfieldsUtils,
    notifications,
    keywordAnalysis,
    keywordAnalysisProgressModel,
    referenceProducts,
    totalCredits,
    Column,
    $t
) {
    'use strict';

    return Column.extend({
        defaults: {
            headerTmpl: 'WriteTextAI_WriteTextAI/grid/columns/text',
            enableComparisonPopup: true,
            statusRunning: 'Running'
        },

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

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

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

            return this;
        },

        /**
         * Initialize tooltip dynamic position.
         */
        initTooltipPositioner: function () {
            $('body').on('mouseenter', '.wtai-text-content', function () {
                var rowIndex = $(this).closest('.data-row').index(),
                    rows = $(this).closest('tbody').children().length;

                if (rowIndex >= rows / 2) {
                    $(this).next('.wtai-comparison').addClass('wtai-show-top');
                } else {
                    $('.wtai-comparison').removeClass('wtai-show-top');
                }
            });
        },

        /**
         * Check if the content should be truncated.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        isTruncated: function (record) {
            var AiContent = record['ai_' + this.index.substring(3)],
                MgContent = record['mg_' + this.index.substring(3)];

            return (
                AiContent && AiContent.length > 100 ||
                MgContent && MgContent.length > 100
            );
        },

        /**
         * Get header css classes.
         */
        getCssClasses: function () {
            if (this.label.startsWith('Magento')) {
                return 'data-grid-th wtai-mg-header';
            } else if (this.label.startsWith('WriteText.ai')) {
                return 'data-grid-th wtai-ai-header';
            }
            
            return 'data-grid-th';
        },

        /**
         * Get writetextai column header label.
         */
        getAiHeader: function () {
            if (this.label.startsWith('WriteText.ai')) {
                return this.label;
            }

            return this.label.replace('Magento', 'WriteText.ai');
        },

        /** @inheritdoc */
        getLabel: function (record) {
            return record[this.index] ? record[this.index].replace(/<[^>]*>/g, '') : '';
        },

        /**
         * Get writetextai column content.
         *
         * @param {Object} record
         * @returns {String}
         */
        getAiContent: function (record) {
            var content = record['ai_' + this.index.substring(3)];

            if (this.index.startsWith('ai_')) {
                content = record[this.index];
            }
            
            content = content ? content : '';

            /* content = textfieldsUtils.convertNewLinesToBr(content); */
            
            return content;
        },

        /**
         * Get magento column header label.
         */
        getMgHeader: function () {
            if (this.label.startsWith('WriteText.ai')) {
                return this.label.replace('WriteText.ai', 'Magento');
            }

            return this.label;
        },

        /**
         * Get magento column content.
         *
         * @param {Object} record
         * @returns {String}
         */
        getMgContent: function (record) {
            var content = record[this.index];

            if (this.index.startsWith('ai_')) {
                content = record['mg_' + this.index.substring(3)];
            }
            
            content = content ? content : '';

            /* content = textfieldsUtils.convertNewLinesToBr(content); */
            
            return content;
        },

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

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

        /**
         * 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);
        },

        /**
         * Get analysis status.
         *
         * @param {Object} record
         * @returns {String}
         */
        getAnalysisStatus: function (record) {
            var isRunning = notifications.statuses().some((status) => {
                return status.status === this.statusRunning &&
                    status.runningIds.indexOf(record.entity_id) !== -1 &&
                    (status.subType === 2 || status.subType === 1);
            }, this);
            var isQueued = notifications.statuses().some((status) => {
                return status.status === this.statusRunning &&
                    status.queuedIds.indexOf(record.entity_id) !== -1 &&
                    (status.subType === 2 || status.subType === 1);
            }, this);
            var isProductOptimizing = keywordAnalysis.statuses().find(function (status) {
                return Number(status.storeId) === Number(referenceProducts.storeId()) &&
                    Number(status.recordId) === Number(record.entity_id) &&
                    status.status === 'Running' &&
                    status.recordType === 'Product';
            });

            if (isRunning || isProductOptimizing) {
                return $t('Keyword analysis currently in progress');
            }

            if (isQueued) {
                return $t('Keyword analysis in queue');
            }

            return '';
        },

        /**
         * 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 keywordAnalysisStatusFailed = record['optimization_status'] === 'Failed' && !this.checkIfOptimizing(record);

                    return failedInBulk || failedInSingle || keywordAnalysisStatusFailed;
                } catch (error) {
                    return false;
                }
            }, this);
        },

        /**
         * Check if keyword analysis is optimizing.
         *
         * @param {Object} record
         * @returns {Boolean}
         */
        checkIfOptimizing: function (record) {
            var isProductOptimizing = keywordAnalysis.statuses().find(function (status) {
                return Number(status.storeId) === Number(referenceProducts.storeId()) &&
                    Number(status.recordId) === Number(record.entity_id) &&
                    status.status === 'Running' &&
                    status.recordType === 'Product';
            });
            var isBulkOptimizing = notifications.statuses().some((status) => {
                return status.status === this.statusRunning &&
                    (status.runningIds.indexOf(record.entity_id) !== -1 ||
                    status.queuedIds.indexOf(record.entity_id) !== -1) &&
                    (status.subType === 2 || status.subType === 1);
            }, this);
            
            return isBulkOptimizing || isProductOptimizing;
        }
    });
});
