/**
 * Fetches the weekly schedule,
 * parses the JSON,
 * picks the current week, and
 * returns the bible texts to read this week.
 *
 * JSON format:
 * [
 *   {
 *      date : 1245745785, // Unixtime, starting Monday of the week
 *      display : "Matthew 27-28 - Mark 1-2",
 *      bibletexts : [
 *        "Mt 27", "Mt 28", "Mr 1", "Mr 2"
 *      ]
 *   },
 *   ...
 * ]
 *
 * Call loadThisWeek() or load()
 */
function LoadWeeklyScheduleJSON(storage) {
}
LoadWeeklyScheduleJSON.prototype = {
  /**
   * Returns the reading for the current week.
   *
   * @param successCallback {Function(display {String}, bibletexts {Array of BibleText})}
   * @param errorCallback
   */
  loadThisWeek : function(successCallback, errorCallback) {
    if (LoadWeeklyScheduleJSON._cur) {
      var cur = LoadWeeklyScheduleJSON._cur;
      successCallback(cur.display, cur.bibletexts);
      return;
    }
    var now = new Date().getTime();
    var weekLength = 7 * 24 * 3600 * 1000; // 1 week, in milliseconds
    this.load(function(json) {
      assert(typeof(json.length) == "number", "wrong JSON format");
      var cur = json.filter(function(week) {
        return week.date.getTime() < now && now < week.date.getTime() + weekLength;
      })[0];
      assert(cur, "Schedule does not contain the current week");
      LoadWeeklyScheduleJSON._cur = cur;
      successCallback(cur.display, cur.bibletexts);
    }, errorCallback);
  },

  /**
   * @param successCallback {Function(data)}
   *    data {Array of {
   *      date {Date}, // Monday of week
   *      display {String}, // Chapters references, human readable, but in English
   *      bibletexts {Array of BibleText}, // Chapters to read
   *    }}
   * @param errorCallback
   */
  load : function(successCallback, errorCallback) {
    var self = this;
    var url = dataURL("weekly-biblereading.json");
    loadURL(url, "json", function(jsonUnparsed) {
      successCallback(self._parse(jsonUnparsed));
    }, errorCallback);
  },

  /**
   * Entry function to parse
   * @param json {JSON or String}   JSON file contents
   * @returns {JSON}
   */
  _parse : function(json) {
    if (typeof(json) == "string") {
      json = JSON.parse(json);
    }
    assert(typeof(json) == "object", "need JSON");

    var result = [];
    json.forEach(function(weekJSON) {
      assert(typeof(weekJSON.date) == "number", "date must be unixtime");
      assert(typeof(weekJSON.display) == "string", "bibletext display must be string");
      assert(typeof(weekJSON.bibletexts.length) == "number", "bibletexts must be array");
      result.push({
        date : new Date(weekJSON.date),
        display : new Date(weekJSON.display),
        bibletexts : weekJSON.bibletexts.map(function(ref) { return new BibleText(ref); }),
      });
    });
    return result;
  },
}

LoadWeeklyScheduleJSON._cur = null;
