/**
 * @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/mark-reviewed',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/utils/edit/generate',
    'WriteTextAI_WriteTextAI/js/edit/buttons',
    'WriteTextAI_WriteTextAI/js/model/edit/invalid-image-popup',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    "Magento_Ui/js/modal/modal"
], function (
    $,
    ko,
    $t,
    Component,
    _,
    markReviewed,
    genKeywordAnalysis,
    keywordAnalysis,
    signalRModel,
    generateUtils,
    buttonsComponent,
    invalidImagePopupModel,
    gallery,
    errorMessagesModel,
    keywords
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            generateParams: {}
        },

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

            self = this;

            const el = document.querySelector('.wtai-invalid-image-popup');
            if (el) {
                $('.wtai-invalid-image-popup > *').applyBindings(this);
            }

            this.initModal();

            invalidImagePopupModel.data.subscribe(function (value) {
                this.generateParams(value);
            }, this);
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super()
                .observe([
                    'generateParams'
                ]);
            
            this.proceedable = ko.computed(function () {
                return gallery.proceedable();
            }, this);

            this.failedImages = ko.computed(function () {
                return gallery.failedImages();
            });

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

            this.invalid = ko.computed(function () {
                return gallery.invalid().slice(0, 10);
            });

            this.notSupported = ko.computed(function () {
                return gallery.notSupported().slice(0, 10);
            });

            this.downloadFailed = ko.computed(function () {
                return gallery.downloadFailed().slice(0, 10);
            });

            this.general = ko.computed(function () {
                return gallery.general().slice(0, 10);
            });

            this.errorMessages = ko.computed(function () {
                return gallery.errorMessages();
            });

            return this;
        },

        /**
         * Initialize modal
         */
        initModal: function () {
            $('.wtai-invalid-image-popup').modal({
                type: 'popup',
                responsive: true,
                title: $t('Some images could not be processed:'),
                modalClass: 'wtai-invalid-image-popup-modal',
                overlayClass: 'modals-overlay wtai-invalid-image-popup-overlay',
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function () {
                        keywordAnalysis.optimizing(false);
                        keywordAnalysis.isUploading(false);
                        keywordAnalysis.imageUploadFailed(false);
                        this.closeModal();
                    }
                }, {
                    text: $t('Proceed'),
                    class: 'action-primary wtai-action-proceed',
                    click: function () {
                        keywordAnalysis.imageUploadFailed(false);
                        if (invalidImagePopupModel.keywordAnalysis()) {
                            keywords.showProgress(true);
                        }
                        self._generate(self.generateParams(), invalidImagePopupModel.keywordAnalysis());
                        this.closeModal();
                    }
                }, {
                    text: $t('Okay'),
                    class: 'action-primary wtai-action-okay',
                    click: function () {
                        this.closeModal();
                    }
                }],
                closed: function () {
                    $('.modals-overlay.wtai-invalid-image-popup-overlay').remove();
                },
                opened: function () {
                    $('.wtai-invalid-image-popup-modal .modal-footer .action-dismiss').toggle(gallery.proceedable());
                    $('.wtai-invalid-image-popup-modal .modal-footer .wtai-action-proceed').toggle(gallery.proceedable());
                    $('.wtai-invalid-image-popup-modal .modal-footer .wtai-action-okay').toggle(!gallery.proceedable());
                }
            });
        },

        /**
         * Generate
         *
         * @param {Object} data
         * @param {boolean} keywordAnalysis
         *
         * @returns {void}
         */
        _generate: function (data, keywordAnalysis = false) {
            /* do not rewrite empty fields */
            if (data.rewrite) {
                data.selected_fields = generateUtils.removeEmptyFields(
                    data.selected_fields
                );
            }
            
            if (keywordAnalysis && generateUtils.checkIfFieldsAndImagesAreEmpty(data)) {
                keywords.noGenerateOnAutoGenerateAfterKo(true);
                generateUtils.requestKeywordAnalysis(self.updateOptimizationUrl, 'Product');
                return;
            }

            /* empty text fields */
            generateUtils.clearFields(data.selected_fields, data.selected_images);

            /* remove error messages */
            errorMessagesModel.messages([]);

            $.ajax({
                url: self.generateUrl,
                type: 'POST',
                data: data,
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: data.selected_fields.includes('page_title'),
                showPageDescriptionLoader: data.selected_fields.includes('page_description'),
                showProductDescriptionLoader: data.selected_fields.includes('product_description'),
                showShortDescriptionLoader: data.selected_fields.includes('short_product_description'),
                showOpenGraphLoader: data.selected_fields.includes('open_graph'),
                showGalleryLoader: data.selected_images.length > 0,
                success: function (response) {
                    if (response.success) {
                        markReviewed.reviewed(response.reviewed);
                        genKeywordAnalysis.views(0);
                    } else {
                        buttonsComponent.prototype.getGenerated(data.selected_fields);
                        if (response.message) {
                            errorMessagesModel.messages.push(response.message);
                        }
                        signalRModel.generating(false);

                        if (response.unauthorized) {
                            window.location.href = response.login_url;
                        }
                    }
                }
            });
        }
    });
});
