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

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

    return Filters.extend({
        defaults: {
            template: 'WriteTextAI_WriteTextAI/grid/filters',
            defaultStoreId: 0,
            customOpenGraph: false,
            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);

            this.errorMessage.subscribe(function (errorMessage) {
                if (errorMessage) {
                    errorMessagesModel.messages.push(errorMessage);
                } else {
                    errorMessagesModel.messages([]);
                }
            }, this);
            
            return this;
        },

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

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

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

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

            if (this.customOpenGraph()) {
                textFields.push('open graph text');
            }

            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 = this.customOpenGraph() ? 5 : 4;
            
            filtersUtils.resetTargetObject(this.applied, this);
            filtersUtils.processRecordIdsFilter(this.applied, this);
            filtersUtils.processRequestIdFilter(this.applied, this);
            filtersUtils.addDefaultWtaiFilters(this.applied, this);
                
            /** remove writetextai_status if it is all and all fields selected */
            appliedClone = _.clone(this.applied);
            if (appliedClone.writetextai_status?.auto_text_optimizations !== undefined) {
                //filtersUtils.resetTargetObject(appliedClone, this);
                filtersUtils.processCustomUrlFilters(appliedClone.writetextai_status, this);
            }

            if (appliedClone.writetextai_status?.ai_fields?.length >= textFields &&
                appliedClone.writetextai_status?.status === 'all' &&
                appliedClone.writetextai_status?.auto_text_optimizations === '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;

            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;
        },

        /**
         * 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 : '';
        }
    });
});
