//
// BEGIN FLOCK GPL
//
// Copyright Flock Inc. 2005-2009
// http://flock.com
//
// This file may be used under the terms of the
// GNU General Public License Version 2 or later (the "GPL"),
// http://www.gnu.org/licenses/gpl.html
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
// for the specific language governing rights and limitations under the
// License.
//
// END FLOCK GPL
//

function doMigrations() {
  var args = [];
  if ("arguments" in window)
    args = window.arguments;

  var oldVersion = args.shift();
  var services = args;

  var serviceLabel  = document.getElementById("migration-info");
  var msgLabel      = document.getElementById("migration-message");
  var progressMeter = document.getElementById("migration-progress");

  for (var i = 0; i < services.length; i++) {
    var service = services[i];

    var basePercent = Math.round((i / services.length) * 100);

    serviceLabel.value = service.migrationName;
    msgLabel.value = "";
    progressMeter.value = basePercent;
    yield false;

    var progressWatcher = {
      divisor: services.length,
      msgLabel: msgLabel,
      progressMeter: progressMeter,
      basePercent: basePercent,
      onUpdate: function(percent, message) {
        dump("PROGRESS: " + percent + " " + message + "\n");
        this.msgLabel.value = message;
        if (percent >= 0) {
          var value = Math.round(this.basePercent + percent / this.divisor);
          this.progressMeter.value = value;
        }
      }
    };

    try {
      var classDesc = service.classDescription;
      dump("Migrate " + classDesc + "\n"); 
      var ctxt = service.startMigration(oldVersion, progressWatcher); 
      while (service.doMigrationWork(ctxt))
        yield false;
      dump("done with " + classDesc + "\n"); 
    }
    catch (e) {
      dump("Exception in migrating " + classDesc + " " + e + "\n");
    }
    finally {
      try {
        service.finishMigration(ctxt);
      }
      catch (e) { }
    }
  }

  serviceLabel.value = "Done";
  msgLabel.value = "";
  progressMeter.value = 100;
  yield true;
}

function migrate() {
  var migrationRunner = doMigrations();

  var run = {
    notify: function(aTimer) {
      if (migrationRunner.next()) {
        aTimer.cancel();
        window.close();
      }
    }
  };

  const nsITimer = Components.interfaces.nsITimer;
  var timer = Components.classes['@mozilla.org/timer;1']
    .createInstance(nsITimer);
  timer.initWithCallback(run, 0, nsITimer.TYPE_REPEATING_SLACK);
}
