import { useArrayData } from 'src/composables/useArrayData';
import { onBeforeMount, ref, watch } from 'vue';

export function useFilterParams(key) {
    if (!key) throw new Error('ArrayData: A key is required to use this composable');
    const params = ref({});
    const orders = ref({});
    const arrayData = ref({});

    onBeforeMount(() => {
        arrayData.value = useArrayData(key);
    });

    watch(
        () => arrayData.value.store?.currentFilter,
        (val, oldValue) => (val || oldValue) && setUserParams(val),
        { immediate: true, deep: true }
    );

    function parseOrder(urlOrders) {
        const orderObject = {};
        if (urlOrders) {
            if (typeof urlOrders == 'string') urlOrders = [urlOrders];
            for (const [index, orders] of urlOrders.entries()) {
                const [name, direction] = orders.split(' ');
                orderObject[name] = { direction, index: index + 1 };
            }
        }
        orders.value = orderObject;
    }

    function setUserParams(watchedParams) {
        if (!watchedParams || Object.keys(watchedParams).length == 0) return;

        if (typeof watchedParams == 'string') watchedParams = JSON.parse(watchedParams);
        if (typeof watchedParams?.filter == 'string')
            watchedParams.filter = JSON.parse(watchedParams.filter);

        watchedParams = { ...watchedParams, ...watchedParams.filter?.where };
        parseOrder(watchedParams.filter?.order);

        delete watchedParams.filter;
        params.value = sanitizer(watchedParams);
    }

    function sanitizer(params) {
        for (const [key, value] of Object.entries(params)) {
            if (key === 'and' && Array.isArray(value)) {
                value.forEach((item) => {
                    Object.assign(params, item);
                });
                delete params[key];
            } else if (value && typeof value === 'object') {
                const param = Object.values(value)[0];
                if (typeof param == 'string') params[key] = param.replaceAll('%', '');
            }
        }
        return params;
    }

    return {
        params,
        orders,
    };
}
