async function fetchEntry(){
    showLoading();
    var name = document.getElementById("name")
    var crs = document.getElementById("3alpha")
    var nlc = document.getElementById("nlc")
    var tiploc = document.getElementById("tiploc")
    var stanox = document.getElementById("stanox")

    var values = {
        name: name.value,
        crs: crs.value,
        nlc: nlc.value,
        tiploc: tiploc.value,
        stanox: stanox.value
    }

    console.log(`Read values: ${JSON.stringify(values)}`)
    
    parseData(values)
}

async function parseData(values){
    if (values.crs != ""){
        var data = await getData("crs", values.crs)
    } else if (values.nlc != ""){
        var data = await getData("nlc", values.nlc)
    } else if (values.tiploc != ""){
        var data = await getData("tiploc", values.tiploc)
    } else if (values.stanox != ""){
        var data = await getData("stanox", values.stanox)
    } else if (values.name != ""){
        var data = await getData("name", values.name)
    } else {
        errorNoData()
        hideLoading()
        return
    }

    displayData(data);
}

async function getData(type, value){
    console.log(`Looking for: ${type} ${value}`)
    try {
        var url = `${window.location.origin}/api/v1/find/${type}/${value}`;
        var resp = await fetch(url);
        console.log(`Response: ${resp.json}`)
        return await resp.json()
    } catch (err) {
        errorFetch(err)
    }
}

async function displayData(data){
    hideLoading();
    if (data.status === "failed" || data == ""){
        errorNotFound()
    }
    document.getElementById("name").value = data['0']['NLCDESC']
    document.getElementById("3alpha").value = data['0']['3ALPHA']
    document.getElementById("nlc").value = data['0']['NLC']
    document.getElementById("tiploc").value = data['0']['TIPLOC']
    document.getElementById("stanox").value = data['0']['STANOX']
//    document.getElementById("stanme").value = data['0']['STANME']  // NOT PRESENT IN CORPUS
}

async function clearForm(){
    document.getElementById("name").value = ""
    document.getElementById("3alpha").value = ""
    document.getElementById("nlc").value = ""
    document.getElementById("tiploc").value = ""
    document.getElementById("stanox").value = ""
    hideLoading();
}

async function showLoading(){
    document.getElementById("loading").style = "display: block;";
}

async function hideLoading(){
    document.getElementById("loading").style = "display: none;";
}

async function errorNoData(){
    console.log("No data entered")
    window.alert("You haven't entered any data")
}

async function errorFetch(err){
    console.log("Error fetching data")
    console.log(err)
}

async function errorNotFound(){
    console.log("Location not found")
    window.alert("No location was found.  Check and try again.")
}