export const getClearValue = (value: any) => {
    if (!value) return "";

    if (typeof value == 'undefined') return "";

    if (Array.isArray(value) || typeof value === 'object') return "";

    if (isNaN(value)) return value.toLowerCase();

    return value
}

export const multipleSort = (data = [], sorts: any, columns: any) => {
    const newSorts = sorts;

    return [...data].sort((a, b) => {
        let i = 0, result = 0;
        while (i < newSorts.length && result === 0) {
            let column = columns?.find((column: any) => column?.key === newSorts[i]?.key);
            let order = (newSorts[i].order == 'asc' ? 1 : -1);

            let valueA;
            let valueB;
            if (column && column?.sortValue) {
                valueA = getClearValue(column?.sortValue(a));
                valueB = getClearValue(column?.sortValue(b));
            } else {
                valueA = getClearValue(a[newSorts[i].key]);
                valueB = getClearValue(b[newSorts[i].key]);
            }

            if (column?.alphanumeric) {
                valueA = normalizeMixedDataValue(valueA);
                valueB = normalizeMixedDataValue(valueB);
            }

            result = order * (valueA < valueB ? -1 : (valueA > valueB ? 1 : 0));
            i++;
        }

        return result;
    })

}

export const normalizeMixedDataValue = (value: any) => {
    const padding = "000000000000000";

    if (!value) return "";
    // Loop over all numeric values in the string and
    // replace them with a value of a fixed-width for
    // both leading (integer) and trailing (decimal)
    // padded zeroes.
    value = value?.toString()?.replace(
        /(\d+)((\.\d+)+)?/g,
        ($0: any, integer: any, decimal: any, $3: any) => {

            // If this numeric value has "multiple"
            // decimal portions, then the complexity
            // is too high for this simple approach -
            // just return the padded integer.
            if (decimal !== $3) {
                return (
                    padding.slice(integer.length) +
                    integer +
                    decimal
                );
            }

            decimal = (decimal || ".0");

            return (
                padding.slice(integer.length) +
                integer +
                decimal +
                padding.slice(decimal.length)
            );

        }
    );

    return value;
}
