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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'WriteTextAI_WriteTextAI/js/model/edit/custom-tone-style',
    'WriteTextAI_WriteTextAI/js/model/edit/settings',
    'WriteTextAI_WriteTextAI/js/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/attributes',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/utils/edit/gallery',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/representative-products',
    'WriteTextAI_WriteTextAI/js/model/edit/preferences',
], function (
    $,
    Component,
    _,
    customToneStyle,
    settings,
    textfields,
    product,
    attributes,
    keywords,
    galleryUtils,
    representativeProducts,
    preferences
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            productId: '',
            storeId: '',
            entityType: 'product'
        },

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

            self = this;

            const el = document.querySelector('.wtai-restore-global-settings');
            if (el) {
                $('.wtai-restore-global-settings > *').applyBindings(this);
            }

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

            product.storeId.subscribe(function (storeId) {
                self.storeId(storeId);
            });
        },

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

            return this;
        },

        /**
         * Restore global settings
         */
        restore: function () {
            var url = this.restoreUrl;

            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                data: {
                    product_id: self.productId(),
                    store_id: self.storeId(),
                    entity_type: self.entityType
                },
                showWriteTextAILoader: true,
                success: function (response) {
                    if (!response.success) {
                        console.log(response.message);
                    } else {
                        console.log(response);
                        self.updateSettings(response);
                        self.saveToneStylePreferences(response);
                    }
                }
            });
        },

        /**
         * Save restored tone/style settings to user preferences
         *
         * @param {Object} response
         */
        saveToneStylePreferences: function (response) {
            if (!self.saveUrl) {
                return;
            }

            var tones = Array.isArray(preferences.tonesSelected())
                ? preferences.tonesSelected()
                : [];
            var style = preferences.stylesSelected() || '';
            var customTone = response && response.data ? (response.data.custom_tone || '') : '';
            var customStyle = response && response.data ? (response.data.custom_style || '') : '';

            if (tones.length <= 0) {
                tones = '';
            }

            $.ajax({
                url: self.saveUrl,
                type: 'POST',
                data: {
                    tones: tones,
                    style: style,
                    custom_tone: customTone,
                    custom_style: customStyle,
                    entity_type: 'global',
                    scope: 'grid'
                },
                dataType: 'json',
                showWriteTextAILoader: false,
                success: function (saveResponse) {
                    if (!saveResponse || !saveResponse.success) {
                        console.log(saveResponse);
                    }
                }
            });
        },

        /**
         * Update settings
         *
         * @param {Object} response
         */
        updateSettings: function (response) {
            var tones = Array.isArray(response.data.tones) ? response.data.tones : [];
            var styles = Array.isArray(response.data.styles) ? response.data.styles : [];

            tones = tones.filter(function (tone) {
                return tone && tone.id !== 'custom';
            });

            settings.guideSteps(response.data.guide_steps);
            settings.tones(tones);
            settings.styles(styles);

            var defaultTones = tones
                .filter(function (tone) {
                    return tone && tone.default;
                })
                .map(function (tone) {
                    return tone.id;
                });

            var defaultStyles = styles
                .filter(function (style) {
                    return style && style.default;
                })
                .map(function (style) {
                    return style.id;
                });

            if (response.data.custom_tone) {
                preferences.tonesSelected(['custom']);
                preferences.tonesSelected.valueHasMutated();
            } else {
                preferences.tonesSelected(defaultTones);
            }

            if (response.data.custom_style) {
                preferences.stylesSelected('custom');
            } else {
                preferences.stylesSelected(defaultStyles.length > 0 ? defaultStyles.shift() : '');
            }

            settings.customTone(response.data.custom_tone);
            settings.customStyle(response.data.custom_style);
            settings.customTone.valueHasMutated();
            settings.customStyle.valueHasMutated();

            preferences.customTone(response.data.custom_tone);
            preferences.customStyle(response.data.custom_style);

            settings.audience(response.data.audience);
            settings.useAiModel(false);
            settings.selectedAiModel('');
            settings.genToneStyleMode('manual');
            settings.descMax(response.data.desc_max);
            settings.descMin(response.data.desc_min);
            settings.excMin(response.data.exc_min);
            settings.excMax(response.data.exc_max);
            textfields.highlightPronouns(
                JSON.parse(response.data.highlight_pronouns.toLowerCase())
            );
            textfields.selectedFields([]);
            keywords.searchIntentSelected(response.data.search_intent.split(','));
            for (let key in response.data.selected_fields) {
                if (response.data.selected_fields.hasOwnProperty(key)) {
                    textfields.selectedFields.push(response.data.selected_fields[key]);
                }
            }

            if (self.entityType === 'product') {
                attributes.productAttributes([]);
                for (let key in response.data.product_attributes) {
                    if (response.data.product_attributes.hasOwnProperty(key)) {
                        attributes.productAttributes.push(
                            response.data.product_attributes[key]
                        );
                    }
                }
                
                /**
                 * IMPORTANT: Always update product attribute list first before the selected
                 * to prioritize preference over global settings
                 */
                attributes.productAttributesSelected(response.data.product_attributes_selected);

                galleryUtils.updateImages(response.data.gallery, response.data.images);
            }

            if (self.entityType === 'category') {
                representativeProducts.productResearchData(response.data.product_research_data === 'true');
            }
        },
    });
});
