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

define([
    'jquery',
    'underscore',
    'Magento_Ui/js/grid/filters/filters',
    'WriteTextAI_WriteTextAI/js/model/grid/reference-products',
    'WriteTextAI_WriteTextAI/js/model/history-log',
    'WriteTextAI_WriteTextAI/js/categories/form/element/status',
    'WriteTextAI_WriteTextAI/js/utils/grid/filters',
    'WriteTextAI_WriteTextAI/js/model/grid/error-messages',
    'WriteTextAI_WriteTextAI/js/model/grid/filter',
    'WriteTextAI_WriteTextAI/js/model/grid/transfer-prompt'
], function (
    $,
    _,
    Filters,
    referenceProducts,
    historyLog,
    wtaiStatusComponent,
    filtersUtils,
    errorMessagesModel,
    filterModel,
    transferPrompt
) {
    'use strict';

    return Filters.extend({
        defaults: {
            template: 'WriteTextAI_WriteTextAI/grid/filters',
            defaultStoreId: 0,
            errorMessage: ''
        },

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

            /**
             * Reset filters object to fix issue where it reset back to previous searches
             */
            filtersUtils.resetTargetObject(this.filters, this);
            filtersUtils.addDefaultWtaiFilters(this.filters, this, true);
            
            this.errorMessage.subscribe(function (errorMessage) {
                if (errorMessage) {
                    errorMessagesModel.messages.push(errorMessage);
                } else {
                    errorMessagesModel.messages([]);
                }
            }, this);
            
            return this;
        },

        /** @inheritdoc */
        initObservable: function () {
            return this._super().observe([
                'errorMessage'
            ]);
        },

        /** @inheritdoc */
        apply: function () {
            filtersUtils.removeParameters();
            wtaiStatusComponent.prototype.outerClick(this.getTextFields());
            this.filters = this.resetTemplatesToAll(this.filters);
            this.filters = this.removeUndefinedStoreFilter(this.filters);
            return this._super();
        },

        /** @inheritdoc */
        clear: function (filter) {
            filtersUtils.removeParameters();
            filterModel.isResetTemplateSelected(true);
            return this._super(filter);
        },

        /**
         * Reset text fields if empty
         *
         * @param {Object} filters
         * @returns {Object}
         */
        getTextFields: function (filters) {
            var textFields = ['category page title', 'category page description', 'category description'];

            return textFields;
        },

        /**
         * Finds filters with a not empty data
         * and sets them to the 'active' filters array.
         *
         * @returns {Filters} Chainable.
         */
        updateActive: function () {
            var appliedClone = [],
                storeId = '',
                applied = [],
                textFields = 3;
            
            filtersUtils.resetTargetObject(this.applied, this);
            filtersUtils.processRecordIdsFilter(this.applied, this);
            filtersUtils.processRequestIdFilter(this.applied, this);
            filtersUtils.addDefaultWtaiFilters(this.applied, this, true);
                
            /** remove writetextai_status if it is all and all fields selected */
            appliedClone = _.clone(this.applied);
            if (appliedClone.writetextai_status?.auto_text_optimizations !== undefined) {
                filtersUtils.processCustomUrlFilters(appliedClone.writetextai_status, this);
            }

            if (appliedClone.writetextai_status?.templates_fields !== 'show_all' &&
                (appliedClone.writetextai_status?.template_selected === undefined ||
                appliedClone.writetextai_status?.template_selected === '')
            ) {
                appliedClone.writetextai_status.filter_by = 'text_status';
                appliedClone.writetextai_status.templates_fields = 'show_all';
                delete appliedClone.writetextai_status.template_selected;
            }

            if (appliedClone.writetextai_status?.ai_fields?.length >= textFields &&
                appliedClone.writetextai_status?.status === 'all' &&
                appliedClone.writetextai_status?.auto_text_optimizations === 'show_all' &&
                appliedClone.writetextai_status?.templates_fields === 'show_all'
            ) {
                delete appliedClone.writetextai_status;
            }

            applied = _.keys(appliedClone);

            this.active = this.elems.filter(function (elem) {
                return _.contains(applied, elem.index);
            });
            
            storeId = this.applied.store_id || this.defaultStoreId;

            // Keep transfer prompt in sync with current store filter for categories
            transferPrompt.storeFilter(storeId);

            /**
             * Used for filtering reference products in bulk generate prompt,
             * uploading images in bulk generation,
             * filtering history logs in grid when closing edit page,
             * and pre selected stores in transfer prompt
             */
            referenceProducts.storeId(storeId);

            historyLog.storeId(storeId);

            return this;
        },

        /**
         * Set store filter to default.
         *
         * @param {Object} filters
         * @returns {Filters} Chainable.
         */
        removeUndefinedStoreFilter: function (filters) {
            if (filters.store_id === undefined) {
                delete filters.store_id;
            }

            return filters;
        },

        /**
         * Reset templates to all if not selected
         *
         * @param {Object} filters
         * @returns {Filters} Chainable.
         */
        resetTemplatesToAll: function (filters) {
            if (filters.writetextai_status?.templates_fields !== 'show_all' &&
                (filters.writetextai_status?.template_selected === undefined ||
                filters.writetextai_status?.template_selected === '')
            ) {
                filterModel.isResetTemplatesToAll(true);
                filters.writetextai_status.templates_fields = 'show_all';
                delete filters.writetextai_status.template_selected;
            }
            filterModel.isResetTemplatesToAll(false);
            return filters;
        },

        /**
         * Get parameter by name
         *
         * @param {String} name
         *
         * @returns {String}
         */
        getParameterValueByName: function (name) {
            var url = new URL(window.location.href),
                searchParams = new URLSearchParams(url.search),
                value = searchParams.get(name);

            return value ? value : '';
        }
    });
});
