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

define([
    'jquery',
    'WriteTextAI_WriteTextAI/js/grid/slug-notice'
], function ($, slugNotice) {
    'use strict';

    /**
     * Process custom url filters
     *
     * The allowed custom url filters are:
     *
     * for keyword_status:
     * - wtai-keyword-optimization: optimized, not_optimized
     * - wtai-keyword-analysis: for_generation, generated, published
     *
     * for text_status:
     * - wtai-text-generation: all, not_generated, writetextai, no_activity
     * - wtai-writetextai-status: Generated, Edited, Reviewed, Transferred, ForTransferring
     *
     * for fields:
     * - wtai-writetextai-fields: page title, page description, product description, excerpt, open graph text,
     *                            category page title, category page description, category description
     *
     * for start_date:
     * - wtai-writetextai-startdate: yyyy-MM-dd{THH:mm:ssZ}
     *
     * for end_date:
     * - wtai-writetextai-enddate: yyyy-MM-dd{THH:mm:ssZ}
     *
     * @param {Object} target
     * @param {Object} self
     *
     * @returns {void}
     */
    function processCustomUrlFilters(target, self)
    {
        if (!target) {
            return;
        }

        let keywordOptParam = self.getParameterValueByName('wtai-keyword-optimization');
        if (keywordOptParam) {
            let validValues = ['optimized', 'not_optimized'];
            if (validValues.includes(keywordOptParam)) {
                target.filter_by = 'keyword_status';
                target.auto_text_optimizations = keywordOptParam;
            }
        }
    
        let keywordAnParam = self.getParameterValueByName('wtai-keyword-analysis');
        if (keywordAnParam) {
            let arrayParam = keywordAnParam.split(',');
            let validValues = ['for_generation', 'generated', 'published'];
            if (arrayParam.every(value => validValues.includes(value))) {
                target.filter_by = 'keyword_status';
                target.keyword_analysis = arrayParam;
            }
        }

        let generationParam = self.getParameterValueByName('wtai-text-generation');
        if (generationParam) {
            let validValues = ['all', 'not_generated', 'writetextai', 'no_activity'];
            if (validValues.includes(generationParam)) {
                target.filter_by = 'text_status';
                target.status = generationParam;
            }
        }

        let writetextaiStatusParam = self.getParameterValueByName('wtai-writetextai-status');
        if (writetextaiStatusParam) {
            let arrayParam = writetextaiStatusParam.split(',');
            let validValues = ['Generated', 'Edited', 'Reviewed', 'Transferred', 'ForTransferring'];
            if (arrayParam.every(value => validValues.includes(value))) {
                target.filter_by = 'text_status';
                target.ai_status = arrayParam;
            }
        }

        let fieldsParam = self.getParameterValueByName('wtai-writetextai-fields');
        if (fieldsParam) {
            let arrayParam = fieldsParam.split(',');
            let validValues = [
                'page title',
                'page description',
                'product description',
                'excerpt',
                'open graph text',
                'category page title',
                'category page description',
                'category description'
            ];
            if (arrayParam.every(value => validValues.includes(value))) {
                target.ai_fields = arrayParam;
            }
        }

        let startDateParam = self.getParameterValueByName('wtai-writetextai-startdate');
        if (startDateParam) {
            target.start_date = startDateParam;
        } else {
            delete target.start_date;
        }

        let endDateParam = self.getParameterValueByName('wtai-writetextai-enddate');
        if (endDateParam) {
            target.end_date = endDateParam;
        } else {
            delete target.end_date;
        }
    }

    /**
     * Process record ids filter
     *
     * @param {Object} target
     * @param {Object} self
     *
     * @returns {void}
     */
    function processRecordIdsFilter(target, self)
    {
        var storeIdParam = self.getParameterValueByName('wtai-store-id');
        if (storeIdParam) {
            if (storeIdParam !== '0') {
                target.store_id = storeIdParam;
            } else {
                delete target.store_id;
            }
        }

        var recordIdsParam = self.getParameterValueByName('wtai-record-ids');
        if (recordIdsParam) {
            target.record_ids = recordIdsParam;
        }
    }

    /**
     * Process request id filter
     *
     * @param {Object} target
     * @param {Object} self
     *
     * @returns {void}
     */
    function processRequestIdFilter(target, self)
    {
        var requestIdParam = self.getParameterValueByName('wtai-request-id');
        if (requestIdParam) {
            target.request_id = requestIdParam;
        }
        var textGenerateStatus = self.getParameterValueByName('wtai-text-generate-status');
        if (textGenerateStatus) {
            target.text_generation_status = textGenerateStatus;
        }
    }

    /**
     * Reset target object
     *
     * @param {Object} target
     *
     * @returns {void}
     */
    function resetTargetObject(target, self)
    {
        let keywordOptParam = self.getParameterValueByName('wtai-keyword-optimization'),
            keywordAnParam = self.getParameterValueByName('wtai-keyword-analysis'),
            generationParam = self.getParameterValueByName('wtai-text-generation'),
            writetextaiStatusParam = self.getParameterValueByName('wtai-writetextai-status'),
            fieldsParam = self.getParameterValueByName('wtai-writetextai-fields'),
            startDateParam = self.getParameterValueByName('wtai-writetextai-startdate'),
            endDateParam = self.getParameterValueByName('wtai-writetextai-enddate'),
            storeIdParam = self.getParameterValueByName('wtai-store-id'),
            recordIdsParam = self.getParameterValueByName('wtai-record-ids'),
            startDate = self.getParameterValueByName('wtai-writetextai-startdate'),
            endDate = self.getParameterValueByName('wtai-writetextai-enddate'),
            requestIdParam = self.getParameterValueByName('wtai-request-id');

        if (
            keywordOptParam ||
            keywordAnParam ||
            generationParam ||
            writetextaiStatusParam ||
            fieldsParam ||
            startDateParam ||
            endDateParam ||
            storeIdParam ||
            recordIdsParam ||
            startDate ||
            endDate ||
            requestIdParam
        ) {
            delete target.sku;
            delete target.entity_id;
            delete target.product_name;
            delete target.type_id;
            delete target.status;
            delete target.visibility;
            delete target.mg_page_description;
            delete target.mg_page_title;
            delete target.mg_product_description;
            delete target.mg_short_product_description;
            
            /** category */
            delete target.name;
            delete target.mg_category_description;
        }

        if (requestIdParam) {
            delete target.writetextai_status;
        }

        if (recordIdsParam &&
            !keywordOptParam &&
            !keywordAnParam &&
            !generationParam &&
            !writetextaiStatusParam &&
            !fieldsParam
        ) {
            delete target.writetextai_status;
        }
    }

    /**
     * Add default writetextai_status filter
     *
     * @param {Object} target
     * @param {Object} self
     * @param {boolean} isCategory
     *
     * @returns {void}
     */
    function addDefaultWtaiFilters(target, self, isCategory = false)
    {
        /* Set default writetextai_status filter when placeholder is true */
        if (!target.writetextai_status) {
            if (isCategory) {
                target.writetextai_status = {
                    ai_fields: [
                        'category page title',
                        'category page description',
                        'category description'
                    ],
                    status: 'all',
                    no_activity_days: 7,
                    auto_text_optimizations: 'show_all',
                    templates_fields: 'show_all',
                    filter_by: 'text_status',
                    initial: true
                };
            } else {
                target.writetextai_status = {
                    ai_fields: [
                        'page title',
                        'page description',
                        'product description',
                        'excerpt',
                        'open graph text',
                        'image_alt_text'
                    ],
                    status: 'all',
                    no_activity_days: 7,
                    auto_text_optimizations: 'show_all',
                    filter_by: 'text_status',
                    templates_fields: 'show_all',
                    alt_text_field: 'image_alt_text',
                    initial: true
                };
            }
        }
    }

    /**
     * Remove parameters from url
     */
    function removeParameters()
    {
        var url = new URL(window.location.href),
            searchParams = new URLSearchParams(url.search),
            keysToRemove = [];

        searchParams.forEach(function (value, key) {
            if (key.startsWith('wtai-') || key.startsWith('wtai_')) {
                keysToRemove.push(key);
            }
        });

        keysToRemove.forEach(function (key) {
            searchParams.delete(key);
        });

        window.history.replaceState({}, '', `${url.origin}${url.pathname}?${searchParams.toString()}`);

        slugNotice.prototype.dismiss();
    }

    return {
        processCustomUrlFilters: processCustomUrlFilters,
        processRecordIdsFilter: processRecordIdsFilter,
        processRequestIdFilter: processRequestIdFilter,
        resetTargetObject: resetTargetObject,
        removeParameters: removeParameters,
        addDefaultWtaiFilters: addDefaultWtaiFilters
    };
});
