import { athenaConfig } from '../global/athena-config.js';

const CATEGORY_EVENT_NAME = 'triggerCategoryPageEvent';

function categoryRedirect(
    categoryId,
    level,
    isInitialRender = false
)
{
    if(isInitialRender) {
        window.location.href = `${athenaConfig.formUrl}?category=${categoryId}&level=${level}`;
    } else {
        const urlParams = new URLSearchParams(window.location.search);

        urlParams.size > 2 ?
            window.location.href = `${athenaConfig.formUrl}?${urlParams.toString()}` :
            window.location.href = `${athenaConfig.formUrl}?category=${categoryId}&level=${level}`;
    }
}

function categoryEventListener()
{
    window.addEventListener(CATEGORY_EVENT_NAME,  event => {
        const { categoryId, level, isInitialRender } = event.detail;

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

        categoryRedirect(categoryId, level, isInitialRender);
    });
}

function getCategoryCustomEvent(
    categoryId,
    level,
    isInitialRender
)
{
    return new CustomEvent(CATEGORY_EVENT_NAME, {
        detail: {
            categoryId: categoryId,
            level: level,
            isInitialRender: isInitialRender
        }
    });
}

export default function category(
    categoryId,
    level,
    isInitialRender = false
)
{
    const validations = {
        'Category ID and Category level must be present!': () => !categoryId || !level,
        'Category ID must be present!': () => !categoryId,
        'Category level must be present!': () => !level,
        'Category ID must be type of integer!': () => isNaN(categoryId),
        'Category level must be type of integer!': () => isNaN(level)
    };

    for (const [message, condition] of Object.entries(validations)) {
        if (condition()) {
            throw new Error(message);
        }
    }

    categoryEventListener();

    window.dispatchEvent(
        getCategoryCustomEvent(
            categoryId,
            level,
            isInitialRender
        )
    );
}