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

define([
    'jquery',
    'uiComponent',
    'underscore',
    'mage/translate',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/categories/model/edit',
    'WriteTextAI_WriteTextAI/js/model/edit/additional-prompt'
], function (
    $,
    Component,
    _,
    $t,
    product,
    categoryEditData,
    additionalPrompt
) {
    'use strict';

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

    return Component.extend({
        defaults: {
            promptValue: '',
            previousPromptValue: '',
            promptLength: 0,
            promptMaxLength: 500,
            productId: '',
            storeId: '',
            entityType: 'Product',
            gettingData: null,
            isGenerateAllowed: false
        },

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

            self = this;

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

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

            additionalPrompt.promptValue.subscribe(function (additionalPrompt) {
                self.promptValue(additionalPrompt);
                self.previousPromptValue(additionalPrompt);
            });
        },

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

            return this;
        },

        /**
         * Get additional prompt length.
         */
        getAdditionalPromptLength: function () {
            var additionalPromptLength = this.promptValue()
                ? this.promptValue().length : 0;

            return (
                additionalPromptLength +
                '/' +
                this.promptMaxLength +
                ' ' +
                $t('Char')
            );
        },
        
        /**
         * Handle input custom audience.
         */
        handleInputAdditionalPrompt: function () {
            if (!self.isGenerateAllowed) {
                return;
            }
            var currentValue = self.promptValue();
            if (currentValue === self.previousPromptValue()) {
                return;
            }
            additionalPrompt.promptValue(currentValue);
            self.saveAdditionalPrompt();
        },

       /**
        * Save additional prompt via AJAX
        */
        saveAdditionalPrompt: function () {
            var self = this;
            var currentValue = self.promptValue();
            var recordId = self.entityType() === 'Product'
            ? self.productId() : categoryEditData.currentCategory().categoryId;


            if (self.gettingData !== null) {
                self.gettingData.abort();
            }

            self.gettingData = $.ajax({
                url: self.saveAdditionalPromptUrl,
                type: 'POST',
                showLoader: false,
                data: {
                    record_id: recordId,
                    store_id: self.storeId(),
                    additional_prompt: currentValue,
                    entity_type: self.entityType()
                },
                success: function (response) {
                    if (!response.success) {
                        console.log(response);
                    }
                },
                error: function (xhr, status, error) {
                    if (status !== 'abort') {
                        errorMessagesModel.messages.push(error);
                    }
                }
            });
        },
    });
});
