import { getLineItemsFlattened } from '@/helpers/line-items-helper';

export default function getQueryStringParameter(key) {
    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const lowerCaseParams = new URLSearchParams();

    urlParams.forEach((value, name) => {
        lowerCaseParams.append(name.toLowerCase(), value);
    });

    return lowerCaseParams.get(key.toLowerCase());
}

export function buildQueryStringParameterFromArrayOfComplexObjects(arrayOfObjects, parameterName) {
    let queryStringParameter = '';
    for (let i = 0; i < arrayOfObjects.length; i++) {
        for (const [key, value] of Object.entries(arrayOfObjects[i])) {
            queryStringParameter += `${parameterName}[${i}].${key}=${value}&`;
        }
    }
    // Remove trailing &
    return queryStringParameter.slice(0, -1);
}

export function getLineItemQueryString(lineItems, parameterName) {
    const queryString = getLineItemsFlattened(lineItems).map((lineItem, index) =>
        `${parameterName}[${index}].partNumber=${lineItem.partNumber}`).join('&');
    return queryString.length !== 0 ? `&${queryString}` : '';
}

export function getPartNumbersListForQueryString(lineItems, parameterName) {
    const queryString = getLineItemsFlattened(lineItems).map((lineItem) =>
        `${parameterName}=${lineItem.partNumber}`).join('&');
    return queryString.length !== 0 ? `&${queryString}` : '';
}

export function getTaxLineItemQueryString(lineItems, parameterName) {
    const queryString = getLineItemsFlattened(lineItems).map((lineItem, index) =>
        `${parameterName}[${index}].partNumber=${lineItem.partNumber}`
        + `&${parameterName}[${index}].laborAmount=${lineItem.laborAmount}`
        + `&${parameterName}[${index}].sellingPrice=${lineItem.sellingPrice}`
        + `&${parameterName}[${index}].kitPrice=${lineItem.kitPrice}`).join('&');
    return queryString.length !== 0 ? `&${queryString}` : '';
}

export function buildURLSearchParams(data) {
    const params = new URLSearchParams();
    Object.entries(data).forEach(([key, value]) => {
        if (value == null) {
            return;
        }
        if (Array.isArray(value)) {
            value.forEach((arrayValue, index) => {
                if (typeof value === 'object') {
                    Object.entries(arrayValue).forEach(([objectKey, objectValue]) => {
                        if (objectValue != null) {
                            params.append(`${key}[${index}].${objectKey}`, `${objectValue}`);
                        }
                    });
                } else {
                    params.append(`${key}[${index}]`, `${value}`);
                }
            });
        } else {
            params.append(key, `${value}`);
        }
    });

    return params;
}
