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

define([
    'jquery',
    'WriteTextAI_WriteTextAI/js/categories/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/edit/textfields',
    'WriteTextAI_WriteTextAI/js/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/edit/gallery',
    'WriteTextAI_WriteTextAI/js/categories/model/signalr',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keywords',
    'WriteTextAI_WriteTextAI/js/model/edit/keywords/keyword-analysis',
    'WriteTextAI_WriteTextAI/js/model/edit/product',
    'WriteTextAI_WriteTextAI/js/model/edit/error-messages',
    'WriteTextAI_WriteTextAI/js/model/edit/generate/currently-generating',
    'mage/translate'
], function (
    $,
    categoriesTextfields,
    textfields,
    signalRModel,
    gallery,
    categoriesSignalRModel,
    keywordsData,
    keywordAnalysisData,
    product,
    errorMessagesModel,
    currentlyGeneratingModel,
    $t
) {
    'use strict';

    /**
     * Remove empty fields.
     *
     * @param {Array} fields
     * @returns {Array}
     */
    function removeEmptyFields(fields)
    {
        var selectedFields = fields || [];
        const fieldsCopy = [...selectedFields];
        fieldsCopy.forEach((field) => {
            switch (field) {
                case 'page_title':
                    if (textfields.mgPageTitle() === '') {
                        selectedFields.splice(
                            selectedFields.indexOf(field),
                            1
                        );
                    }
                    break;
                case 'page_description':
                    if (textfields.mgPageDescription() === '') {
                        selectedFields.splice(
                            selectedFields.indexOf(field),
                            1
                        );
                    }
                    break;
                case 'product_description':
                    if (textfields.mgProductDescription() === '') {
                        selectedFields.splice(
                            selectedFields.indexOf(field),
                            1
                        );
                    }
                    break;
                case 'short_product_description':
                    if (textfields.mgProductShortDescription() === '') {
                        selectedFields.splice(
                            selectedFields.indexOf(field),
                            1
                        );
                    }
                    break;
                case 'open_graph':
                    if (textfields.mgOpenGraph() === '') {
                        selectedFields.splice(
                            selectedFields.indexOf(field),
                            1
                        );
                    }
                    break;
            }
        });

        return selectedFields;
    }

    /**
     * Remove images with empty alt.
     *
     * @param {Array} selectedImages
     * @returns {Array}
     */
    function removeImageWithEmptyAlt(selectedImages)
    {
        var images = gallery.images();
        var selectedImages = selectedImages;

        try {
            images.forEach((image) => {
                if (image.alt === '') {
                    selectedImages.splice(
                        selectedImages.indexOf(image.id),
                        1
                    );
                }
            });
        } catch (e) {
            return selectedImages;
        }

        return selectedImages;
    }

    /**
     * Clear text fields.
     *
     * @param {Array} selectedFields
     * @param {Array} selectedImages
     *
     * @returns {void}
     */
    function clearFields(selectedFields, selectedImages)
    {
        signalRModel.showMessage(false);
        signalRModel.errorFields([]);
        signalRModel.errorMessage('');
        signalRModel.selectedFields(selectedFields);
        signalRModel.imagesGenerating(selectedImages);
        signalRModel.imagesGenerated([]);
        signalRModel.fieldsGenerated({
            page_title: null,
            page_description: null,
            product_description: null,
            excerpt: null,
            open_graph: null
        });
        if (Array.isArray(selectedFields)) {
            selectedFields.forEach((field) => {
                switch (field) {
                    case 'page_title':
                        textfields.pageTitle('');
                        signalRModel.fieldsGenerated()['page_title'] = false;
                        $('#wtaiPageTitleMask').removeClass('wtai-generated');
                        break;

                    case 'page_description':
                        textfields.pageDescription('');
                        signalRModel.fieldsGenerated()[
                            'page_description'
                        ] = false;
                        $('#wtaiPageDescMask').removeClass('wtai-generated');
                        break;

                    case 'product_description':
                        textfields.productDescription('');
                        signalRModel.fieldsGenerated()[
                            'product_description'
                        ] = false;
                        $('#wtaiProductDescMask + .mce-tinymce').removeClass('wtai-generated');
                        $('#wtaiProductDescMask + .tox-tinymce').removeClass('wtai-generated');
                        $('#wtaiProductDescMask + .tox-hugerte').removeClass('wtai-generated');
                        break;

                    case 'short_product_description':
                        textfields.productShortDescription('');
                        signalRModel.fieldsGenerated()['excerpt'] = false;
                        $('#wtaiExcerptMask + .mce-tinymce').removeClass('wtai-generated');
                        $('#wtaiExcerptMask + .tox-tinymce').removeClass('wtai-generated');
                        $('#wtaiExcerptMask + .tox-hugerte').removeClass('wtai-generated');
                        break;

                    case 'open_graph':
                        textfields.openGraph('');
                        signalRModel.fieldsGenerated()['open_graph'] = false;
                        $('#wtaiOpenGraphMask').removeClass('wtai-generated');
                        break;
                }
            });
        }
        /** Ensure this is set last to prevent premature notification display. */
        signalRModel.generating(true);
        /** add identifier to currently generating record identifiers */
        var identifier = 'Product' + '_' +  product.productId() + '_' + product.storeId();
        var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
        if (!currentlyGeneratingRecordIdentifiers.includes(identifier)) {
            currentlyGeneratingRecordIdentifiers.push(identifier);
            currentlyGeneratingModel.recordIdentifiers(currentlyGeneratingRecordIdentifiers);
        }
    }

    /**
     * Remove identifier from currently generating record identifiers.
     *
     * @param {String} type
     *
     * @returns {void}
     */
    function removeIdentifierFromCurrentlyGeneratingRecordIdentifiers(type)
    {
        var identifier = type + '_' +  product.productId() + '_' + product.storeId();
        var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
        currentlyGeneratingRecordIdentifiers.splice(currentlyGeneratingRecordIdentifiers.indexOf(identifier), 1);
        currentlyGeneratingModel.recordIdentifiers(currentlyGeneratingRecordIdentifiers);
    }

    /**
     * Clear text fields.
     *
     * @param {Array} selectedFields
     * @param {Boolean} rewrite
     *
     * @returns {void}
     */
    function clearCategoryFields(selectedFields, rewrite)
    {
        categoriesSignalRModel.showMessage(false);
        categoriesSignalRModel.errorFields([]);
        categoriesSignalRModel.errorMessage('');
        categoriesSignalRModel.selectedFields(selectedFields);
        categoriesSignalRModel.fieldsGenerated({
            page_title: null,
            page_description: null,
            category_description: null
        });
        if (Array.isArray(selectedFields)) {
            selectedFields.forEach((field) => {
                switch (field) {
                    case 'page_title':
                        if (!rewrite || (rewrite && categoriesTextfields.mgPageTitle() !== '')) {
                            categoriesTextfields.pageTitle('');
                            $('#wtaiPageTitleMask').removeClass('wtai-generated');
                        }
                        break;

                    case 'page_description':
                        if (!rewrite || (rewrite && categoriesTextfields.mgPageDescription() !== '')) {
                            categoriesTextfields.pageDescription('');
                            $('#wtaiPageDescMask').removeClass('wtai-generated');
                        }
                        break;

                    case 'category_description':
                        if (!rewrite || (rewrite && categoriesTextfields.mgCategoryDescription() !== '')) {
                            categoriesTextfields.categoryDescription('');
                            $('#wtaiCategoryDescMask + .mce-tinymce').removeClass('wtai-generated');
                            $('#wtaiCategoryDescMask + .tox-tinymce').removeClass('wtai-generated');
                            $('#wtaiCategoryDescMask + .tox-hugerte').removeClass('wtai-generated');
                        }
                        break;
                }
            });
        }
        /** Ensure this is set last to prevent premature notification display. */
        categoriesSignalRModel.generating(true);
        /** add identifier to currently generating record identifiers */
        var identifier = 'Category' + '_' +  product.productId() + '_' + product.storeId();
        var currentlyGeneratingRecordIdentifiers = currentlyGeneratingModel.recordIdentifiers();
        if (!currentlyGeneratingRecordIdentifiers.includes(identifier)) {
            currentlyGeneratingRecordIdentifiers.push(identifier);
            currentlyGeneratingModel.recordIdentifiers(currentlyGeneratingRecordIdentifiers);
        }
    }

    /**
     * Check if fields and images are empty.
     *
     * @param {Object} data
     * @returns {boolean}
     */
    function checkIfFieldsAndImagesAreEmpty(data)
    {
        return data.selected_fields.length === 0 && data.selected_images.length === 0;
    }

    /**
     * Request keyword analysis.
     *
     * @param {String} requestUrl
     * @param {String} entityType
     *
     * @returns {void}
     */
    function requestKeywordAnalysis(requestUrl, entityType)
    {
        var isImageUploadFailed = keywordAnalysisData.imageUploadFailedIdentifier();
        var requestData = {
            record_id: product.productId(),
            store_id: product.storeId(),
            entity_type: entityType,
            url: product.productUrl(),
            name: product.productName(),
            product_type: product.productType(),
            /** seed_keywords: keywordsData.selectedKeywords(), */
            search_intent_selected: keywordsData.searchIntentSelected()
        }
        if (!isImageUploadFailed) {
            requestData.image_id = keywordsData.thumbnailId();
        }
        $.ajax({
            url: requestUrl,
            type: 'POST',
            data: requestData,
            dataType: 'json',
            showLoader: false,
            success: function (response) {
                if (!response.success) {
                    keywordAnalysisData.optimizationFailed(true);
                    keywordAnalysisData.optimizing(false);
                    keywordAnalysisData.customOptFailedText(response.error);
                    errorMessagesModel.messages.push(response.error);
                    keywordsData.showProgress(false);
                } else {
                    keywordAnalysisData.customProgressText($t('Queued for keyword analysis'));
                }
            }
        }).always(function () {
            keywordAnalysisData.imageUploadFailedIdentifier(false);
        });
    }

    return {
        removeEmptyFields: removeEmptyFields,
        clearFields: clearFields,
        removeImageWithEmptyAlt: removeImageWithEmptyAlt,
        clearCategoryFields: clearCategoryFields,
        checkIfFieldsAndImagesAreEmpty: checkIfFieldsAndImagesAreEmpty,
        requestKeywordAnalysis: requestKeywordAnalysis,
        removeIdentifierFromCurrentlyGeneratingRecordIdentifiers: removeIdentifierFromCurrentlyGeneratingRecordIdentifiers
    }
});
