init()

/* Supporting Functions */
async function init() {
    var stn = await getQuery("stn");
    console.log(`Looking up: ${stn}`);
    var sv = await getQuery("sv");
    console.log(`Staff Verstion: ${sv}`);
    if (sv === 'true') {
        console.log("Staff Version not supported yet")
    } else {
        try {
            var data = await publicLdb(stn)
            console.log("Fetched LDB Data")
        } catch (err) {
            var data = null
            console.log("Unable to fetch LDB data")
        } finally {
            console.log(data)
            parseLdb(data)
        }
    }
}

async function getQuery(param) {
    var params = new URLSearchParams(window.location.search)
    var query = params.get(param)
    if (query) {
        return query
    } else {
        return 'false'
    }
}

async function publicLdb(stn) {
    var url = `http://${window.location.host}/api/v1/ldb/${stn}`;
    var resp = await fetch(url);
    return await resp.json();
}

async function setHeaders(title,time){
    var prefix = `OwlBoard - `
    document.title = `${prefix}${title}`
    document.getElementById("station_name").innerHTML = title

}

async function parseLdb(data) {
    var stationName = data.GetStationBoardResult.locationName;
    console.log(`Data ready for ${stationName}`);
    var generateTime = await data.GetStationBoardResult.generatedAt;
    console.log(`Data prepared at ${generateTime}`)
    setHeaders(stationName, generateTime);
}