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

define([
    'jquery',
    'WriteTextAI_WriteTextAI/js/utils/total-credits',
    'WriteTextAI_WriteTextAI/js/utils/pro-badge',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/model/grid/prompt',
    'WriteTextAI_WriteTextAI/js/model/grid/notifications',
    'WriteTextAI_WriteTextAI/js/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/progress',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/currently-generating',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr'
], function (
    $,
    totalCreditsUtils,
    proBadgeUtils,
    gallery,
    prompt,
    notifications,
    textfields,
    keywordsProgressModel,
    signalRModel,
    currentlyGeneratingModel,
    categoriesSignalRModel
) {
    'use strict';

    /**
     * Remove single request.
     *
     * @param {String} requestId
     * @param {Object} self
     *
     * @returns {void}
     */
    function removeSingleRequest(requestId, self)
    {
        $.ajax({
            url: self.removeSingleRequestUrl,
            type: 'POST',
            data: {
                request_id: requestId
            },
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (!response.success) {
                    console.log(response.message);
                }
            }
        });
    }

    /**
     * Get new access token.
     *
     * @param {Object} self
     *
     * @returns {void}
     */
    function getNewAccessToken(self)
    {
        var url = self.getNewAccessTokenUrl;
    
        self.isGettingNewToken = true;
        $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (response.success) {
                    self.accessToken(response.access_token);
                }
            }
        }).always(function () {
            self.isGettingNewToken = false;
        });
    }
    
    /**
     * Update text fields.
     *
     * @param {String} field
     * @param {String} value
     * @param {Object} self
     *
     * @returns {void}
     */
    function updateField(field, value, self)
    {
        switch (field) {
            case self.pageTitle:
                textfields.pageTitle(value);
                break;
            case self.pageDescription:
                textfields.pageDescription(value);
                break;
            case self.productDescription:
                /** removed typing animation in wysiwyg due to scrolling lag */
                /** textfields.productDescription(value); */
                break;
            case self.excerpt:
                /** removed typing animation in wysiwyg due to scrolling lag */
                /** textfields.productShortDescription(value); */
                break;
            case self.openGraph:
                textfields.openGraph(value);
                break;
        }
    }

    /**
     * Get text field value.
     *
     * @param {String} field
     * @returns {String}
     */
    function getField(field, self)
    {
        var value = '';

        switch (field) {
            case self.pageTitle:
                value = textfields.pageTitle();
                break;
            case self.pageDescription:
                value = textfields.pageDescription();
                break;
            case self.productDescription:
                value = textfields.productDescription();
                break;
            case self.excerpt:
                value = textfields.productShortDescription();
                break;
            case self.openGraph:
                value = textfields.openGraph();
                break;
        }

        return value;
    }

    /**
     * Get images.
     *
     * @param {Object} self
     * @returns {void}
     */
    function getCredits(self)
    {
        $.ajax({
            url: self.getCreditsUrl,
            type: 'GET',
            data: {},
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                totalCreditsUtils.updatePremium(response);
                proBadgeUtils.updateProBadge(response);
            }
        });
    }

    /**
     * Get index field.
     *
     * @param {String} field
     * @param {Object} self
     *
     * @returns {String}
     */
    function getIndexField(field, self)
    {
        var value = '';

        switch (field) {
            case self.pageTitle:
                value = 'page_title';
                break;
            case self.pageDescription:
                value = 'page_description';
                break;
            case self.productDescription:
                value = 'product_description';
                break;
            case self.excerpt:
                value = 'excerpt';
                break;
            case self.openGraph:
                value = 'open_graph';
                break;
        }

        return value;
    }

    /**
     * Get images.
     *
     * @param {Number} productId
     * @param {Number} storeId
     * @param {Object} self
     *
     * @returns {void}
     */
    function getImages(productId, storeId, self)
    {
        $.ajax({
            url: self.getImagesUrl,
            type: 'POST',
            data: {
                product_id: productId,
                store_id: storeId
            },
            dataType: 'json',
            showWriteTextAILoader: true,
            showGalleryLoader: true,
            success: function (response) {
                if (response.success) {
                    gallery.images(response.images);
                }
            }
        });
    }

    /**
     * Process single request.
     *
     * @param {Object} messageEntry
     * @param {Object} self
     *
     * @returns {void}
     */
    function processSingleRequest(messageEntry, self, isSingleRequest = false)
    {
        if (!isSingleRequest) {
            if (!messageEntry.encodedMsg.id.includes('Ideas')) {
                if (messageEntry.encodedMsg.status === 'Completed' &&
                    messageEntry.encodedMsg.completed === 0 &&
                    messageEntry.encodedMsg.total === 1 &&
                    prompt.autoOptimizeKeywords()
                ) {
                    /** do nothing */
                    signalrUtils.getCredits(self);
                    return;
                }
                if (messageEntry.encodedMsg.status === 'Completed' &&
                    messageEntry.encodedMsg.completed === 1 &&
                    messageEntry.encodedMsg.failed === 0 &&
                    prompt.autoOptimizeKeywords()
                ) {
                    self.processFailedOptimizationMessage(messageEntry);
                } else {
                    if (messageEntry.encodedMsg.status === 'Failed' &&
                        messageEntry.encodedMsg.completed === 1 &&
                        messageEntry.encodedMsg.failed === 0
                    ) {
                        notifications.addGenerateFailedStatus(messageEntry.encodedMsg);
                    } else {
                        notifications.addStreamStatus(messageEntry);
                    }
                }
            }
        } else {
            /**PROGRESS GOES HERE FOR EDIT KO + GENERATE && GENERATE */
            if (messageEntry.encodedMsg.subType === 0 &&
                currentlyGeneratingModel.recordIdentifiers().includes(
                    messageEntry.encodedMsg.recordType + '_' +  self.productId() + '_' + self.storeId()
                ) &&
                Number(self.storeId()) === Number(messageEntry.encodedMsg.storeId)
            ) {
                if (messageEntry.encodedMsg.status === 'Pending') {
                    signalRModel.editTitleStatusText('Queued for text generation...');
                } else {
                    signalRModel.editTitleStatusText('Generating text...');
                }
            }
            keywordsProgressModel.addOrUpdateStatus(messageEntry.encodedMsg);
            if (messageEntry.encodedMsg.status === 'Completed' &&
                messageEntry.encodedMsg.completed === 1  &&
                messageEntry.encodedMsg.failed === 0
            ) {
                /** Removed to fix issue showing progress bar when single generating via ko */
                /** signalrUtils.removeSingleRequest(messageEntry.encodedMsg.id, self); */
            }
            notifications.statuses.remove(function (status) {
                return status.id === messageEntry.encodedMsg.id;
            });
        }
    }

    /**
     * Check if the status is cancelling.
     *
     * @param {Object} data
     *
     * @returns {Boolean}
     */
    function isCancelling(data)
    {
        var status = data.status || '';

        return status === 'Cancelling';
    }

    return {
        removeSingleRequest: removeSingleRequest,
        getNewAccessToken: getNewAccessToken,
        updateField: updateField,
        getField: getField,
        getCredits: getCredits,
        getIndexField: getIndexField,
        getImages: getImages,
        processSingleRequest: processSingleRequest,
        isCancelling: isCancelling
    };
});
