var jsonfile = require('jsonfile');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;

jsonfile.readFile("okcgsw/schedule/schedule.json", function(err, data) {
    if (err) console.error(err);
    else {
        console.log(data);
    }
})

return;
function get(url, callback) {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "json";
    xhr.onload = function() {
      var status = xhr.status;
      if (status == 200) {
        callback(null, xhr.responseText);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

get("http://www.si.com/pbp/liveupdate?sport=NBA&date=2016-5-28&pbp=false&box=false&json=1", function(err, data) {
    console.log("writing schedule data");
    
    var file = 'okcgsw/schedule/schedule.json'
    jsonfile.writeFile(file, data, function(err) {
        if (err) {
            console.error(err);
        }
    });
});

var okcgsw_url = "http://www.si.com/pbp/liveupdate?json=1&sport=basketball%2Fnba&id=1637626&box=true&pbp=true&linescore=true";
var key = 401;
var index = {};
var index_file = "okcgsw/live/index-2-" + new Date().getTime() + ".json";

setInterval(function() {
    get(okcgsw_url, function(err, data) {
        if (err) {
            console.error(err);
        }
        else {
            var d = new Date();
            console.log("writing live poll to file ", key, d.getTime());
            var time = d.getTime()
            var filename = "okcgsw/live/" + time + ".json";
            index[key] = d.getTime();
            
            key += 1;
            jsonfile.writeFile(filename, data, function(err) {
                if (err)  {
                    console.error(err);
                }
            })
            
            console.log("updating index file ");
            jsonfile.writeFile(index_file, index, function(err) {
                if (err)  {
                    console.error(err);
                }
            })
            
        }
    })
}, 10000)
