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

define([
    'jquery',
    'ko',
    'mage/translate',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/progress'
], function (
    $,
    ko,
    $t,
    Component,
    _,
    productData,
    editData,
    categoriesEditData,
    keywordAnalysis,
    keywords,
    progress
) {
    'use strict';

    /**
     * @var {Component} self
     */
    var self;

    return Component.extend({
        defaults: {
            commentHidden: false,
            recordId: 0,
            storeId: 0,
            showProgress: false,
            cancelling: false
        },

        isShowProgressChanged: false,
        isCommentHiddenChanged: false,

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

            self = this;

            categoriesEditData.currentCategory.subscribe(function (category) {
                this.recordId(category.categoryId);
                this.storeId(category.storeId);
            }, this);

            editData.currentProduct.subscribe(function (product) {
                this.recordId(product.productId);
                this.storeId(product.storeId);
            }, this);

            keywords.showProgress.subscribe(function (value) {
                this.showProgress(value);
            }, this);

            this.showProgress.subscribe(function (value) {
                if (!this.isShowProgressChanged) {
                    keywords.showProgress(value);
                }
            }, this);

            progress.commentHidden.subscribe(function (value) {
                this.isCommentHiddenChanged = true;
                this.commentHidden(value);
                this.isCommentHiddenChanged = false;
            }, this);

            this.commentHidden.subscribe(function (value) {
                if (!this.isCommentHiddenChanged) {
                    progress.commentHidden(value);
                }
            }, this);

            this.progressStatus.subscribe(function (status) {
                if (status && status.status === 'Cancelled') {
                    keywords.showProgress(false);
                    keywordAnalysis.isUploading(false);
                    keywordAnalysis.optimizing(false);
                }
            }, this);

        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'storeId',
                'recordId',
                'showProgress',
                'commentHidden',
                'cancelling'
            ]);

            this.status = ko.computed(function () {
                var status = keywordAnalysis.statuses().find(function (status) {
                    return Number(status.storeId) === Number(this.storeId()) && status.recordId === this.recordId();
                }.bind(this));

                if (status) {
                    return status;
                }

                return {};
            }, this);

            this.progressPerc = ko.computed(function () {
                return (this.status().completed / this.status().total) * 100;
            }, this);

            this.progressText = ko.computed(function () {
                if (this.status().statusDisplay) {
                    return this.status().statusDisplay;
                }

                if (this.status().status === 'Completed') {
                    var koCompletedText = $t('Keyword analysis completed');
                    if (keywordAnalysis.autoGenerateOrRewriteChecked() &&
                        keywordAnalysis.optimizingId() === this.recordId()
                    ) {
                        koCompletedText = $t('Generating text...');
                    }
                    return koCompletedText;
                }

                return keywordAnalysis.customProgressText() || $t('Keyword analysis currently in progress');
            }, this);

            this.showFailedPage = ko.computed(function () {
                return this.status().status === 'Failed' || (
                    !keywordAnalysis.optimizing() &&
                    !keywordAnalysis.isUploading() &&
                    !keywordAnalysis.optimized() &&
                    keywordAnalysis.imageUploadFailed()
                );
            }, this);

            this.showTryAgain = ko.computed(function () {
                return this.showFailedPage();
            }, this);

            this.failedText = ko.computed(function () {
                if (keywordAnalysis.optimizationFailed()) {
                    return keywordAnalysis.customOptFailedText();
                }

                return $t('The previous keyword analysis processing failed, you can restart to try again.');
            });

            this.showPipelines = ko.computed(function () {
                return !keywordAnalysis.optimizing() &&
                    !keywordAnalysis.isUploading() &&
                    keywordAnalysis.optimized() &&
                    !keywordAnalysis.optimizationFailed() &&
                    !keywordAnalysis.imageUploadFailed();
            }, this);

            this.isUploading = ko.computed(function () {
                return keywordAnalysis.isUploading();
            }, this);

            this.progressStatus = ko.computed(function () {
                return progress.getStatusByRecord(this.storeId(), this.recordId(), this.entityType);
            }, this);

            this.cancelable = ko.computed(function () {
                var status = this.progressStatus();
                return status && status.status === 'Pending';
            }, this);

            return this;
        },

        /**
         * @returns {void}
         */
        hideComment: function () {
            this.commentHidden(true);
        },

        /**
         * @returns {void}
         */
        showComment: function () {
            this.commentHidden(false);
        },

        /**
         * Cancel optimization.
         */
        cancel: function () {
            keywordAnalysis.optimizing(false);
            keywordAnalysis.optimized(false);
            keywordAnalysis.optimizationFailed(false);
            keywordAnalysis.imageUploadFailed(false);

            var statuses = keywordAnalysis.statuses();
            keywordAnalysis.statuses(statuses.filter(function (status) {
                return Number(status.storeId) !== Number(self.storeId()) || status.recordId !== self.recordId();
            }));

            keywords.showProgress(false);
        },

        /**
         * Cancel request.
         *
         * @return {void}
         */
        cancelRequest: function () {
            this.cancelling(true);
            $.ajax({
                url: self.cancelUrl,
                type: 'POST',
                data: {
                    id: this.progressStatus().id
                },
                dataType: 'json',
                showLoader: true,
                success: function (response) {
                    this.cancelling(false);
                    if (!response.success) {
                        console.log(response.message);
                    }
                }.bind(this),
                error: function (response) {
                    this.cancelling(false);
                    console.log(response.message);
                }.bind(this)
            });
        },

        /**
         * Start optimization.
         */
        tryAgain: function () {
            keywordAnalysis.optimizing(true);
            keywordAnalysis.optimized(false);
            keywordAnalysis.optimizationFailed(false);
            keywordAnalysis.imageUploadFailed(false);

            var statuses = keywordAnalysis.statuses();
            keywordAnalysis.statuses(statuses.filter(function (status) {
                return Number(status.storeId) !== Number(self.storeId()) || status.recordId !== self.recordId();
            }));

            $.ajax({
                url: self.deleteOptimizationUrl,
                type: 'POST',
                data: {
                    record_id: self.recordId(),
                    store_id: self.storeId(),
                    entity_type: self.entityType
                },
                dataType: 'json',
                showLoader: false,
                success: function (response) {
                    if (response.success) {
                        $.ajax({
                            url: self.updateOptimizationUrl,
                            type: 'POST',
                            data: {
                                record_id: self.recordId(),
                                store_id: self.storeId(),
                                entity_type: self.entityType,
                                url: productData.productUrl(),
                                name: productData.productName(),
                                image_id: keywords.thumbnailId(),
                                /** seed_keywords: keywords.selectedKeywords(), */
                                search_intent_selected: keywords.searchIntentSelected()
                            },
                            dataType: 'json',
                            showLoader: false,
                            success: function (response) {
                                if (!response.success) {
                                    keywordAnalysis.optimizationFailed(true);
                                    keywordAnalysis.optimizing(false);
                                    keywordAnalysis.customOptFailedText(response.error);
                                }
                            }
                        });
                    }
                }
            });
        }
    });
});
