/**
 * IP location service client
 *
 * @author Pierre Hubert
 */

/**
 * Apply location information where requested
 */
async function apply_location_information() {
  for (const el of document.querySelectorAll("locateip")) {
    if (el.hasAttribute("updated"))
        continue;

    el.setAttribute("updated", "1");

    try {
        if(typeof IP_LOCATION_API === undefined)
            throw new Error("IP location service is undefined!");

        const URL = IP_LOCATION_API + "?ip=" + el.getAttribute("ip");
        const res = await (await fetch(URL)).json();

        if (res.country_code === undefined || res.country_name === undefined)
            throw new Error("IP location information unavailable!");
        
        let loc = "<img src='/assets/img/countries/" + res.country_code.toLowerCase() + ".png' style='height: 1em;' /> ";

        if (res.region_name !== undefined && res.region_name !== "")
            loc += res.region_name + " (" + res.country_name + ")";
        else
            loc += res.country_name;
        
        el.innerHTML = loc;
        
    } catch(e) {
        console.error(e);
        el.innerHTML = "Unavailable";
    }
  }
}

window.addEventListener("load", () => apply_location_information());