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

define([
    'jquery',
    'ko',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/transfer/settings',
    'WriteTextAI_WriteTextAI/js/utils/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/settings',
    'WriteTextAI_WriteTextAI/js/model/edit/mark-reviewed',
    'WriteTextAI_WriteTextAI/js/model/edit/preferences',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/edit/review-status',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'Magento_Ui/js/modal/confirm',
    'mage/translate'
], function (
    $,
    ko,
    Component,
    _,
    editData,
    product,
    textfields,
    errorMessagesModel,
    transferSettings,
    textfieldsUtils,
    settings,
    markReviewed,
    preferences,
    gallery,
    reviewStatus,
    keywordAnalysis,
    confirm,
    $t
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            previewButtonSelector: '.wtai-preview-button',
            defaultStoreId: 0,
            productId: '',
            storeId: '',
            pageTitle: '',
            pageDescription: '',
            productDescription: '',
            productShortDescription: '',
            openGraph: '',
            selectedFields: [],
            eventsInitialized: false,
            directiveRegex: [],
            descriptionDirectiveExists: false,
            shortDescriptionDirectiveExists: false,
            selectedStores: [],
            guideSteps: false,
            customTone: '',
            customStyle: '',
            selectedTones: [],
            selectedStyles: '',
            selectedAudience: [],
            statuses: {
                pageTitleGenerateStatus: false,
                pageDescriptionGenerateStatus: false,
                productDescriptionGenerateStatus: false,
                productShortDescriptionGenerateStatus: false,
                openGraphGenerateStatus: false,
                pageTitleTransferStatus: false,
                pageDescriptionTransferStatus: false,
                productDescriptionTransferStatus: false,
                productShortDescriptionTransferStatus: false,
                openGraphTransferStatus: false
            }
        },
        updateFields: [],

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

            self = this;

            /* get product and store id */
            product.productId.subscribe(function (productId) {
                self.productId(productId);
            });
            product.storeId.subscribe(function (storeId) {
                self.storeId(storeId);
            });

            product.directiveRegex.subscribe(function (directiveRegex) {
                if (directiveRegex && directiveRegex.length > 0) {
                    self.directiveRegex(directiveRegex);
                } else {
                    self.directiveRegex([]);
                }
            });

            product.descriptionDirectiveExists.subscribe(
                function (descriptionDirectiveExists) {
                    self.descriptionDirectiveExists(descriptionDirectiveExists);
                }
            );

            product.shortDescriptionDirectiveExists.subscribe(
                function (shortDescriptionDirectiveExists) {
                    self.shortDescriptionDirectiveExists(
                        shortDescriptionDirectiveExists
                    );
                }
            );

            /* get field values */
            textfields.pageTitle.subscribe(function (pageTitle) {
                self.pageTitle(pageTitle);
            });
            textfields.pageDescription.subscribe(function (pageDescription) {
                self.pageDescription(pageDescription);
            });
            textfields.productDescription.subscribe(
                function (productDescription) {
                    /* productDescription = textfieldsUtils.convertNewLinesToBr(productDescription); */
                    self.productDescription(productDescription);
                }
            );
            textfields.productShortDescription.subscribe(
                function (productShortDescription) {
                   /* productShortDescription = textfieldsUtils.convertNewLinesToBr(productShortDescription); */
                    self.productShortDescription(productShortDescription);
                }
            );
            textfields.openGraph.subscribe(function (openGraph) {
                self.openGraph(openGraph);
            });

            /* get selected fields */
            textfields.selectedFields.subscribe(function (selectedFields) {
                self.selectedFields([]);

                for (let key in selectedFields) {
                    if (selectedFields.hasOwnProperty(key)) {
                        self.selectedFields.push(selectedFields[key]);
                    }
                }
            });

            textfields.statuses.subscribe(function (statuses) {
                self.statuses(statuses);
            });

            editData.opened.subscribe(function (opened) {
                if (opened && !self.eventsInitialized) {
                    self.bindPreviewButton();
                    self.eventsInitialized = true;
                }
            });

            settings.guideSteps.subscribe(function (guideSteps) {
                self.guideSteps(guideSteps);
            });

            transferSettings.selectedStores.subscribe(
                function (selectedStores) {
                    self.selectedStores([]);
                    for (let key in selectedStores) {
                        if (selectedStores.hasOwnProperty(key)) {
                            self.selectedStores.push(selectedStores[key]);
                        }
                    }
                }
            );

            /* get preferences */
            preferences.customTone.subscribe(function (customTone) {
                self.customTone(customTone);
            });

            preferences.customStyle.subscribe(function (customStyle) {
                self.customStyle(customStyle);
            });

            preferences.tonesSelected.subscribe(function (tonesSelected) {
                self.selectedTones([]);
                for (let key in tonesSelected) {
                    if (tonesSelected.hasOwnProperty(key)) {
                        self.selectedTones.push(tonesSelected[key]);
                    }
                }
            });

            preferences.stylesSelected.subscribe(function (stylesSelected) {
                self.selectedStyles(stylesSelected);
            });

            preferences.audienceSelected.subscribe(function (audienceSelected) {
                self.selectedAudience([]);
                for (let key in audienceSelected) {
                    if (audienceSelected.hasOwnProperty(key)) {
                        self.selectedAudience.push(audienceSelected[key]);
                    }
                }
            });
        },

        /** @inheritdoc */
        initObservable: function () {
            this._super().observe([
                'productId',
                'storeId',
                'pageTitle',
                'pageDescription',
                'productDescription',
                'productShortDescription',
                'openGraph',
                'selectedFields',
                'directiveRegex',
                'descriptionDirectiveExists',
                'shortDescriptionDirectiveExists',
                'selectedStores',
                'guideSteps',
                'customTone',
                'customStyle',
                'selectedTones',
                'selectedStyles',
                'selectedAudience',
                'statuses'
            ]);

            this.isNotAllStoreView = ko.computed(function () {
                return parseInt(this.storeId()) !== this.defaultStoreId;
            }, this);

            this.canSave = ko.computed(function () {
                const fieldFunctions = {
                    'page_title': {
                        original: textfields.originalPageTitle,
                        edited: textfields.pageTitle
                    },
                    'page_description': {
                        original: textfields.originalPageDescription,
                        edited: textfields.pageDescription
                    },
                    'product_description': {
                        original: textfields.originalProductDescription,
                        edited: textfields.productDescription
                    },
                    'short_product_description': {
                        original: textfields.originalProductShortDescription,
                        edited: textfields.productShortDescription
                    },
                    'open_graph': {
                        original: textfields.originalOpenGraph,
                        edited: textfields.openGraph
                    }
                },
                    fields = [
                        'page_title',
                        'page_description',
                        'product_description',
                        'short_product_description',
                        'open_graph'
                    ];
                this.updateFields = [];
                var canSaveText = fields.some(function (field) {
                    if (fieldFunctions[field] &&
                                fieldFunctions[field].original() !== fieldFunctions[field].edited() &&
                                fieldFunctions[field].edited() !== ''
                            ) {
                        return true;
                    }
                }),
                    canSaveMedia = gallery.images().some(function (data) {
                        if (data.original_writetext_alt !== data.writetext_alt &&
                            data.writetext_alt !== '') {
                            return true;
                        }
                    });

                fields.forEach(function (item) {
                    if (fieldFunctions[item] &&
                            fieldFunctions[item].original() !== fieldFunctions[item].edited() &&
                            fieldFunctions[item].edited() !== ''
                        ) {
                        this.updateFields.push(item);
                    }
                }, this);

                return canSaveText || canSaveMedia;
            }, this);

            this.canTransfer = ko.computed(function () {
                const fieldFunctions = {
                    'page_title': {
                        generated: this.statuses().pageTitleGenerateStatus
                    },
                    'page_description': {
                        generated: this.statuses().pageDescriptionGenerateStatus
                    },
                    'product_description': {
                        generated: this.statuses().productDescriptionGenerateStatus
                    },
                    'short_product_description': {
                        generated: this.statuses().productShortDescriptionGenerateStatus
                    },
                    'open_graph': {
                        generated: this.statuses().openGraphGenerateStatus
                    }
                };
                var canTransferText = this.selectedFields().some(function (field) {
                    if (fieldFunctions[field] && fieldFunctions[field].generated) {
                        return true;
                    }
                }),
                    canTransferMedia = gallery.images().some(function (data) {
                        return gallery.selectedImages().includes(data.id) && data.writetext_alt !== '';
                    }),
                    isOptimizing = keywordAnalysis.statuses().find(function (status) {
                        return Number(status.storeId) === Number(self.storeId()) && status.recordId === self.productId() && status.status === 'Running';
                    }),
                    isProductOptimizing = Number(keywordAnalysis.optimizingId()) === Number(this.productId()) &&
                        Number(keywordAnalysis.optimizingStoreId()) === Number(this.storeId()),
                    keywordAnalysisOngoing = (keywordAnalysis.optimizing() ||
                    keywordAnalysis.isUploading()) &&
                        !keywordAnalysis.optimized() &&
                        !keywordAnalysis.optimizationFailed() &&
                        !keywordAnalysis.imageUploadFailed();

                if (isOptimizing || (keywordAnalysisOngoing && isProductOptimizing)) {
                    return false;
                }

                return canTransferText || canTransferMedia;
            }, this);

            return this;
        },

        /**
         * Bind preview button.
         */
        bindPreviewButton: function () {
            $(this.previewButtonSelector).on('click', function () {
                var previewUrl = $(this).data('link');

                window.open(previewUrl, '_blank');
            });
        },

        /**
         * Save text to api.
         */
        save: function () {
            var url = self.saveUrl,
                productId = self.productId(),
                storeId = self.storeId(),
                pageTitle = self.pageTitle(),
                pageDescription = self.pageDescription(),
                productDescription = self.productDescription(),
                productShortDescription = self.productShortDescription(),
                openGraph = self.openGraph(),
                selectedFields = self.selectedFields(),
                customTone = self.customTone(),
                customStyle = self.customStyle(),
                selectedTones = self.selectedTones(),
                selectedStyles = self.selectedStyles(),
                selectedAudience = self.selectedAudience(),
                images = gallery.images();
            var stringImages = JSON.stringify(images);
            errorMessagesModel.messages([]);
            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    product_id: productId,
                    store_id: storeId,
                    page_title: pageTitle,
                    page_description: pageDescription,
                    product_description: productDescription,
                    product_short_description: productShortDescription,
                    open_graph: openGraph,
                    selected_fields: selectedFields,
                    custom_tone: customTone,
                    custom_style: customStyle,
                    tones: selectedTones,
                    styles: selectedStyles,
                    audience: selectedAudience,
                    images: stringImages,
                    update_fields: self.updateFields
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: true,
                showPageDescriptionLoader: true,
                showProductDescriptionLoader: true,
                showShortDescriptionLoader: true,
                showOpenGraphLoader: true,
                showGalleryLoader: true,
                success: function (response) {
                    if (!response.success) {
                        errorMessagesModel.messages.push(response.message);
                    } else {
                        if (response.params.fields && response.params.fields.length > 0) {
                            markReviewed.reviewed(false);
                        }
                        textfields.originalPageTitle(pageTitle);
                        textfields.originalPageDescription(pageDescription);
                        textfields.originalProductDescription(
                            productDescription
                        );
                        textfields.originalProductShortDescription(
                            productShortDescription
                        );
                        textfields.originalOpenGraph(openGraph);
                        if (response.images) {
                            gallery.images(response.images);
                        }
                        if (response.textfields_statuses && response.textfields_statuses.length > 0) {
                            textfields.statuses({
                                pageTitleGenerateStatus: response.textfields_statuses.page_title_generated,
                                pageDescriptionGenerateStatus: response.textfields_statuses.page_description_generated,
                                productDescriptionGenerateStatus: response.textfields_statuses.product_description_generated,
                                productShortDescriptionGenerateStatus: response.textfields_statuses.short_product_description_generated,
                                openGraphGenerateStatus: response.textfields_statuses.open_graph_generated,
                                pageTitleTransferStatus: response.textfields_statuses.page_title_transferred,
                                pageDescriptionTransferStatus: response.textfields_statuses.page_description_transferred,
                                productDescriptionTransferStatus: response.textfields_statuses.product_description_transferred,
                                productShortDescriptionTransferStatus: response.textfields_statuses.short_product_description_transferred,
                                openGraphTransferStatus: response.textfields_statuses.open_graph_transferred
                            });
                        }
                    }
                }
            });
        },

        /**
         * Transfer text to Magento.
         */
        transfer: function () {
            confirm({
                title: $.mage.__('Transfer selected to Magento'),
                content: self.confirmContent,
                modalClass: 'wtai-modal wtai-bulk-transfer-popup wtai-transfer wtai-edit',
                actions: {
                    confirm: function () {
                        self._transfer();
                    }
                },
                buttons: [{
                    text: $t('Cancel'),
                    class: 'action-secondary action-dismiss',
                    click: function (event) {
                        this.closeModal(event);
                    }
                }, {
                    text: $t('OK'),
                    class: 'action-primary action-accept',
                    click: function (event) {
                        if (
                            $('#wtaiEditTransferForm').data('validator') &&
                            $('#wtaiEditTransferForm').validation() &&
                            $('#wtaiEditTransferForm').validation('isValid')
                        ) {
                            this.closeModal(event, true);
                        }
                    }
                }]
            });
        },

        /**
         * Transfer text to Magento.
         */
        _transfer: function () {
            var url = self.transferUrl,
                productId = self.productId(),
                storeId = self.storeId(),
                pageTitle = self.pageTitle(),
                pageDescription = self.pageDescription(),
                productDescription = self.productDescription(),
                productShortDescription = self.productShortDescription(),
                openGraph = self.openGraph(),
                selectedFields = self.selectedFields(),
                selectedStores = self.selectedStores(),
                selectedImages = gallery.selectedImages(),
                images = gallery.images();

            errorMessagesModel.messages([]);

            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    product_id: productId,
                    store_id: storeId,
                    page_title: pageTitle,
                    page_description: pageDescription,
                    product_description: productDescription,
                    product_short_description: productShortDescription,
                    open_graph: openGraph,
                    selected_fields: selectedFields,
                    selected_stores: selectedStores,
                    selected_images: selectedImages,
                    images: images
                },
                dataType: 'json',
                showWriteTextAILoader: true,
                showPageTitleLoader: selectedFields.includes('page_title'),
                showPageDescriptionLoader: selectedFields.includes('page_description'),
                showProductDescriptionLoader: selectedFields.includes('product_description'),
                showShortDescriptionLoader: selectedFields.includes('short_product_description'),
                showOpenGraphLoader: selectedFields.includes('open_graph'),
                showGalleryLoader: selectedImages.length > 0,
                success: function (response) {
                    var fields = response.fields;
                    
                    if (response.success) {
                        markReviewed.reviewed(response.reviewed);
                        if (response.use_default) {
                            textfields.useDefault({
                                pageTitle: selectedFields.includes('page_title') ?
                                    response.use_default.page_title : textfields.useDefault().pageTitle,
                                pageDescription: selectedFields.includes('page_description') ?
                                    response.use_default.page_description : textfields.useDefault().pageDescription,
                                productDescription: selectedFields.includes('product_description') ?
                                    response.use_default.product_description : textfields.useDefault().productDescription,
                                productShortDescription: selectedFields.includes('short_product_description') ?
                                    response.use_default.short_product_description : textfields.useDefault().productShortDescription,
                                openGraph: selectedFields.includes('open_graph') ?
                                    response.use_default.open_graph : textfields.useDefault().openGraph
                            });
                        }
                        
                        if (selectedStores.map(String).includes(String(storeId))) {
                            textfieldsUtils.updateCurrentFields(fields, selectedFields, {
                                'page_title': pageTitle,
                                'page_description': pageDescription,
                                'product_description': productDescription,
                                'short_product_description': productShortDescription,
                                'open_graph': openGraph
                            });
                            self.descriptionDirectiveExists(
                                response.directives.product_description
                            );
                            self.shortDescriptionDirectiveExists(
                                response.directives.short_product_description
                            );
                            gallery.images(response.images);
                        }
                    } else {
                        errorMessagesModel.messages.push(response.message);
                    }
                        
                    reviewStatus.reviewStatus(response.updatedReview);
                }
            });
        },

        /**
         * Check if media or directive exists.
         */
        hasMediaOrDirective: function () {
            if (self.selectedFields().includes('product_description')) {
                return self.descriptionDirectiveExists();
            }
            if (self.selectedFields().includes('short_product_description')) {
                return self.shortDescriptionDirectiveExists();
            }
        }
    });
});
