/**
 * @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',
], function (
    $,
    Component,
    _,
    customToneStyle,
    settings,
    textfields,
    product,
    attributes,
    keywords,
    galleryUtils,
    representativeProducts
) {
    '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 {
                        self.updateSettings(response);
                    }
                }
            });
        },

        /**
         * Update settings
         *
         * @param {Object} response
         */
        updateSettings: function (response) {
            customToneStyle.customTone(response.data.custom_tone);
            customToneStyle.customStyle(response.data.custom_style);
            settings.guideSteps(response.data.guide_steps);
            settings.tones(response.data.tones);
            settings.styles(response.data.styles);
            settings.audience(response.data.audience);
            settings.useAiModel(false);
            settings.selectedAiModel('');
            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');
            }
        },
    });
});
