// const months = [
//     'January', 'February', 'March', 'April', 'May', 'June',
//     'July', 'August', 'September', 'October', 'November', 'December'
// ];

function fn_QueryStringToJSON(qs) {
    qs = qs || location.search.slice(1);

    var pairs = qs.split('&');
    var result = {};
    var is_result = false;
    pairs.forEach(function (p) {
        var pair = p.split('=');
        var key = pair[0];
        var value = decodeURIComponent(pair[1] || '');
        if (key.length > 0) {
            is_result = true;

            if (result[key]) {
                if (Object.prototype.toString.call(result[key]) === '[object Array]') {
                    result[key].push(value);
                } else {
                    result[key] = [result[key], value];
                }
            } else {
                result[key] = value;
            }
        }
    });

    if (is_result) {
        return JSON.parse(JSON.stringify(result));
    } else { return null }
}

function jsonToQueryString(json) {
    return '?' +
        Object.keys(json).map(function (key) {
            return encodeURIComponent(key) + '=' +
                encodeURIComponent(json[key]);
        }).join('&');
}

function fn_ErrorFound(err) {
    notie.alert({ type: 'error', text: `${err}`, stay: false, position: 'bottom' })
}

function fn_EncryptResponse(response) {
    try {
        if (response.status >= 200 && response.status < 300) {
            let clone = response.clone();
            var data = clone.json();
            return Promise.resolve(data).then(function (res) { return res });
        } else {
            return Promise.reject(new Error(response.statusText))
        }
    } catch (objErrorText) {
        fn_CatchError(objErrorText);
    }
}

function fn_ConvertImageToBase64(input, fn) {
    if (input.files && input.files[0]) {
        count = 1
        $.each(input.files, function () {
            let file = this
            var reader = new FileReader();

            reader.onload = function (e) {
                return e.target.result
                // fn(e.target.result, (count == input.files.length))
                count++;
            }

            reader.readAsDataURL(file);

        })
    }
}

async function fn_GetAsyncCall(api) {
    var response = await fetch(api, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

async function fn_PostAsyncCall(api, jsonBody) {
    var response = fetch(api, {
        method: 'POST',
        body: jsonBody,
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

async function fn_PatchAsyncCall(api, jsonBody) {
    var response = fetch(api, {
        method: 'PATCH',
        body: jsonBody,
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

async function fn_DeleteAsyncCall(api) {
    var response = fetch(api, {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' }
    }).then(fn_EncryptResponse).then(function (response) {
        return response
    }).catch(function (err) {
        return { 'ok': 0, "error": err }
    });

    return response;
}

function fn_RatingStars(avg_rating) {
    // console.log(avg_rating)
    avg_rating = parseInt(avg_rating)
    half = 5 - avg_rating
    stars = ""
    for (var index = 0; index < avg_rating; index++) {
        stars += `<i class="fas fa-star"></i>`
    }

    for (var index = 0; index < half; index++) {
        stars += `<i class="far fa-star"></i>`
    }

    return stars
}

function fn_Loading(text) {
    return `<img width="20" src="/static/images/loading.gif" style="display:inline-block;" />&nbsp;&nbsp;${text}`
}

function getVerticalScrollPercentage(elm) {
    var p = elm.parentNode
    return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight) * 100
}

function fn_DateToStr(str_dt) {
    if (str_dt != "-") {
        let dt = new Date(str_dt)
        if (dt.getFullYear() == '1970') {
            return 'NA'
        } else {
            return `${dt.getDate()}-${months[dt.getMonth()]}-${dt.getFullYear()}`
        }
    } return ""
}

function fn_FormToJson(form, validationColumns = []) {
    const formData = new FormData(form);
    let jsonObject = {};

    formData.forEach((value, key) => {
        jsonObject[key] = value;
    });

    // ["name","mobile"]
    // {"name":"Neeraj Pathak","mobile":"","email":"parvatiandsons2@gmail.com","message":"asdasd"}
    let emptyColumns = []

    for (var i = 0; i < validationColumns.length; i++) {
        var columnName = validationColumns[i];
        if (jsonObject.hasOwnProperty(columnName) && jsonObject[columnName] === "") {
            emptyColumns.push(columnName);
        }
    }

    return [emptyColumns, jsonObject];
}

function fn_CheckValue(val) {
    if (val != null) {
        if (typeof val != 'undefined') {
            return val
        }
    }

    return ''
}

// Function to format keys to capital case and remove underscores
function formatKeys(jsonObj) {
    var formattedObj = {};
    for (var key in jsonObj) {
        var formattedKey = key.replace(/_/g, ' ').toLowerCase().replace(/\b\w/g, function (char) {
            return char.toUpperCase();
        });
        formattedObj[formattedKey] = jsonObj[key];
    }
    return formattedObj;
}
// // Function to create HTML table from JSON data
function createTableFromJson(jsonObj) {
    let nextData = null
    var tableHTML = '<table class="table table-bordered">';
    // Create table rows
    currentData = jsonObj;
    for (var key in jsonObj) {
        // var value = Array.isArray(jsonObj[key]) ? jsonObj[key].join(', ') : jsonObj[key];
        var value = jsonObj[key];
        if (key != "Id") {
            if (value != null) {
                // Check if value is an object
                if (typeof value === 'object') {
                    nextData = value
                    value = `<a href="javascript:void()" >View Details</a>`;
                }
                if (key == "Pickup On") {
                    value = fn_DateToStr(value);
                }

                if (nextData == null) {
                    tableHTML += '<tr><th>' + key + '</th><td>' + value + '</td></tr>';
                }
            }

            if (nextData != null) {
                if (Array.isArray(nextData)) {
                    nextData.forEach(function (obj) {
                        tableHTML += createInnerTableFromJson(key, formatKeys(obj))
                    })
                } else {
                    tableHTML += createInnerTableFromJson(key, formatKeys(nextData))
                }
            }
        }
    }

    tableHTML += '</table>';
    return tableHTML;
}

function createInnerTableFromJson(group_name, jsonObj) {
    let tableHTML = `<tr><th colspan="2" class="text-center">${group_name}</th></tr>`
    for (var key in jsonObj) {
        var value = jsonObj[key];
        if (key != "Id") {
            if (value != null) {
                // Check if value is an object
                if (typeof value === 'object') {
                    value = `NA`;
                }

                if (key == "Date") {
                    value = fn_DateToStr(value);
                }

                tableHTML += '<tr><th>' + key + '</th><td>' + value + '</td></tr>';
            }
        }

    }

    return tableHTML
}


async function fn_AsyncConvertImageToBase64(input) {
    return new Promise((resolve, reject) => {
        if (input.files && input.files[0]) {
            let count = 1;
            const results = [];

            Array.from(input.files).forEach(async (file) => {
                const result = await readFileAsync(file);
                results.push(result);
                if (count === input.files.length) {
                    resolve(results);
                }
                count++;
            });
        } else {
            reject(new Error("No files selected."));
        }
    });
}

function readFileAsync(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (error) => {
            reject(error);
        };

        reader.readAsDataURL(file);
    });
}

