/**
 * Check Url Category Params
 *
 * @returns {{category: null, level: null, isCategory: boolean}}
 */
function isUrlParamsCategory()
{
    const urlParams = new URLSearchParams(window.location.search);
    const categoryVariables = JSON.parse(localStorage.getItem('category'));

    if(categoryVariables) {
        const { category, level } = categoryVariables;

        if(urlParams.has('category') && urlParams.has('level')) {
            const categoryUrl = urlParams.get('category');
            const levelUrl = urlParams.get('level');

            if(parseInt(categoryUrl) !== parseInt(category) || parseInt(level) !== parseInt(levelUrl)) {
                return {
                    category: categoryUrl,
                    level: levelUrl,
                    isCategory: true
                };
            }
        }

        return {
            category: category,
            level: level,
            isCategory: true
        };
    }

    if (urlParams.has('category') && urlParams.has('level')) {
        const category = urlParams.get('category');
        const level = urlParams.get('level');

        localStorage.setItem(
            'category',
            JSON.stringify({
                category: category,
                level: level
            })
        );

        return {
            category: category,
            level: level,
            isCategory: true
        };
    }

    return {
        category: null,
        level: null,
        isCategory: false
    };
}


/**
 * Check if Category Search is Active
 *
 * @param data
 */
function isCategorySearchActive(data) {
    let isCategory = false;

    const {
        category: urlParamCategory,
        level: urlParamLevel,
        isCategory: urlParamIsCategory
    } = isUrlParamsCategory();

    if(data['q'] && data['q'].length > 0 && data['q'] !== 'undefined' || data['image'] && data['image'].length > 0) {
        return false;
    }

    if(
        data.hasOwnProperty('category') ||
        data.hasOwnProperty('q') && !data['q'] ||
        data.hasOwnProperty('q') && typeof data['q'] !== 'undefined' ||
        urlParamIsCategory
    ) {
        delete data['service'];
        delete data['search'];
        delete data['q'];
        delete data['image'];

        data['service'] = 'category/data';
        data['category'] = urlParamCategory ;
        data['level'] = urlParamLevel;

        isCategory = true;
    }

    return isCategory;
}

export default isCategorySearchActive;