/**
 * (c) COPYRIGHT AVIATION SOFTWARE INC. 2003-2011
 */

/**
 * Manages multiple Updater instances
 *
 */
function UpdaterMgr() {
    this.updaters = {};
    this.debugging = typeof top.debug == 'object'  && top.debug != null && typeof top.debug.log == 'function';
    if ( this.debugging ) {
        top.debug.log('initialized', this);
    }
    this.toString = toStringLog;
}

UpdaterMgr.prototype.debug = function(ls) {
  ls = ls || new LogStream();
  ls.println("UpdaterMgr {");
  ls.entab();
  this.debugUpdaters(ls);
  ls.detab();
  ls.println("}");
  return ls;
}

UpdaterMgr.prototype.debugUpdaters = function(ls) {
  ls.println("updaters: {");
  ls.entab();
  for ( var i in this.updaters ) {
    if ( typeof this.updaters[i] == 'object' && typeof this.updaters[i].debug == 'function') {
      ls.print("[" + i + "] => ");
      this.updaters[i].debug(ls);
      ls.println(",");
    }
  }
  ls.detab();
  ls.println("}");
  return ls;
}


UpdaterMgr.prototype.create = function(id, disconnect, path, progress_type, action, target) {
    var token = this.generateToken();
    var updater = new Updater(
                        id,
                        disconnect,
                        path,
                        {
                            progress_type: progress_type,
                            action: action,
                            updaterToken: token,
                            updaterTarget: target
                        }
                    );
    this.store( token, updater );
    return token;
}

UpdaterMgr.prototype.generateToken = function() {
    var dt = new Date();
    return dt.getTime();
}

UpdaterMgr.prototype.store = function( key, obj ) {
    if ( obj instanceof Updater ) {
        this.updaters[key] = obj;
    }
    return {};
}

UpdaterMgr.prototype.retrieve = function( key ) {
    return this.updaters[key] instanceof Updater ? this.updaters[key] : null;
}

UpdaterMgr.prototype.stop = function( key ) {
    var updater = this.retrieve(key);
    if ( updater != null ) {
        if ( this.debugging ) {
            top.debug.log('stopping ' + key, this);
        }
        updater.stop();
    }
}

UpdaterMgr.prototype.stopAll = function () {
    for ( var i in this.updaters ) {
        this.stop(i);
    }
}

window.UpdaterMgr = UpdaterMgr;
window.updaterMgr = new UpdaterMgr();
