const headers = {
    'Content-Type': 'application/json'
}

const get = async <T>(url: string) => {
    const response = await fetch(url, {
        method: 'GET',
        headers
    })
    return await response.json() as T
}

const post = async <T>(url: string, body: any) => {
    const response = await fetch(url, {
        method: 'POST',
        headers,
        body
    })
    return await response.json() as T
}

const post1 = async <T>(url: string) => {
    const response = await fetch(url, {
        method: 'POST',
    })
    return await response.json() as T
}

const postForm = async <T>(url: string, body: any) => {
    const response = await fetch(url, {
        method: 'POST',
        body: body
    })
    return await response.json() as T
}

const put = async <T>(url: string, body: any) => {
    const response = await fetch(url, {
        method: 'PUT',
        headers,
        body
    })
    return await response.json() as T
}

const _delete = async <T>(url: string) => {
    const response = await fetch(url, {
        method: 'DELETE',
        headers
    })
    return await response.json() as T
}

const getQueryStringParameters = <T>() => {
    // Get each key/value pair entry
    let key_value = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    // JSON object to hold key value pairs
    let parameters : any = {};
    // Iterate through each key_value splitting them as key = value add each as a JSON entry
    for (let i = 0; i < key_value.length; i++) {
        let parameter = key_value[i].split('=');
        parameters[parameter[0]] = parameter[1];
    }
    // // Return the JSON object
    return parameters as T
}

export const http = {
    get,
    post,
    post1,
    postForm,
    put,
    delete: _delete,
    getQueryStringParameters
}