let scheduleFetchInterval;
let scheduleURL;


onmessage = function(e) {
    let msgType = e.data.msgType;

    if (msgType === "ScheduleFetchConfig") {
        scheduleURL = e.data.scheduleURL;
        scheduleFetchInterval = 1000 * e.data.scheduleFetchInterval;

        console.log("Message: " + msgType);
        console.log('Using schedule url: ' + scheduleURL);
        console.log('Fetching data each [ms]: ' + scheduleFetchInterval);
    }
};


function scheduleFetch() {
    let now = new Date();

    if (scheduleURL) {
        fetch(scheduleURL).then(
            b => b.json()).then(
                j => postMessage({msgType: "ScheduleUpdate",
                                  schedule: j,
                                  timestamp: now}))
            .catch(e => console.log(e.message));
    }
    // TODO: Hook up schedule processing functions
}





// TODO: Fix run once and then periodic
scheduleFetch();

(function periodicScheduleFetch() {
    setTimeout(function() {
        scheduleFetch();
        periodicScheduleFetch();
    }, scheduleFetchInterval);
})();
