// Enable delays
const delay = ms => new Promise(res => setTimeout(res, ms));

init()

/* Supporting Functions */
async function init() {
    var stn = await getQuery("stn");
    log(`init: Looking up: ${stn}`);
    var sv = await getQuery("sv");
    log(`init: Staff Version: ${sv}`);
    if (sv === 'true') {
        log("init: Staff Version not supported yet.")
        log("init: Unable to proceed.")
    } else {
        try {
            var data = await publicLdb(stn)
            log("init: Fetched LDB Data")
            parseLdb(data)
        } catch (err) {
            var data = null
            log("init: Unable to fetch LDB 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 = `${window.location.origin}/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
    document.getElementById("fetch_time").innerHTML = time.toLocaleTimeString()
}

async function parseLdb(data) {
    if (data.ERROR == "NOT_FOUND") { // Station not found
        clearLoading();
        document.getElementById("error_notice").style = "display: block;";
        document.getElementById("err_not_found").style = "display: block;";
        setHeaders("Not Found",new Date())
    } else if (data == false) {  // No data for station
        clearLoading();
        document.getElementById("error_notice").style = "display: block;";
        document.getElementById("err_no_data").style = "display:block;";
        setHeaders("No Data",new Date())
    } else if (data == "err") {  // Connection Error
        clearLoading();
        document.getElementById("error_notice").style = "display: block;";
        document.getElementById("err_conn").style = "display: block;";
        setHeaders("Connection Error",new Date())
        await delay(5000);
        log(`parseLdb: Waited five seconds, reloading`)
        location.reload()
    } else {
        buildPage(data);
    }
}

// Hide loading spinner
async function clearLoading() {
    document.getElementById("loading").style = "display: none;";
}

// Build and Display Functions
async function buildPage(data) {
    var stationName = data.GetStationBoardResult.locationName;
    log(`buildPage: Data ready for ${stationName}`);
    var generateTime = new Date(await data.GetStationBoardResult.generatedAt);
    log(`buildPage: Data prepared at ${generateTime.toLocaleString()}`)
    setHeaders(stationName, generateTime);
    // Check for notices and if true pass to function
    if (data.GetStationBoardResult.nrccMessages) {
        displayNotices(data.GetStationBoardResult.nrccMessages.message)
    }
    if (typeof data.GetStationBoardResult.trainServices == 'undefined') {
        displayNoTrains()
    } else {
        // Function here to Parse train services and display.
    }
}

async function displayNotices(notices) {
    // Input: data.GetStationBoardResult.nrccMessages.messages
    // Processing: For each message, create a <p> inside #notices.
    //             If there is more than one notice, scroll between them.
    // Output: Only to DOM.
    //document.getElementById("notices").innerHTML = notices;
}

async function displayNoTrains() {
    document.getElementById('no_services').style = "display: block;";
    clearLoading();
}

async function displayTrains() {
    return
}

// Log Helper
function log(msg) {
    var time = new Date().toISOString();
    console.log(`${time} - ${msg}`)
}