baja/virt/VirtualGateway.js

/**
 * @copyright 2015 Tridium, Inc. All Rights Reserved.
 * @author Gareth Johnson
 */

/**
 * Defines {@link baja.VirtualGateway}.
 * @module baja/virt/VirtualGateway
 */
define([ "bajaScript/comm",
        "bajaScript/baja/virt/VirtualComponentSpace",
        "bajaScript/baja/comp/Component",
        "bajaScript/baja/comm/Callback" ], 
        function (baja, VirtualComponentSpace, Component, Callback) {

  "use strict";
  
  var subclass = baja.subclass,
      callSuper = baja.callSuper,
      objectify = baja.objectify;

  /**
   * Represents a `baja:VirtualGateway` in BajaScript.
   *
   * @class
   * @alias baja.VirtualGateway
   * @extends baja.Component
   */  
  var VirtualGateway = function VirtualGateway() {
    callSuper(VirtualGateway, this, arguments);
    this.$virtualSpace = null;
  };
  
  subclass(VirtualGateway, Component);
      
  /**
   * Return the Virtual Space for the Gateway. 
   *
   * @returns {baja.VirtualComponentSpace}
   */
  VirtualGateway.prototype.getVirtualSpace = function () {    
    return this.$virtualSpace;
  };
  
  /**
   * Load the Slots for the VirtualGateway.
   * 
   * @see baja.Component#loadSlots
   */
  VirtualGateway.prototype.loadSlots = function (obj) {
    obj = objectify(obj);
    obj.cb = new Callback(obj.ok, obj.fail, obj.batch);
  
    var that = this,
        cb = obj.cb,
        initCb;
              
    function callSuperLoadSlots() {    
      that.$initPromise
        .then(function () {
          callSuper("loadSlots", VirtualGateway, that, [ obj ]);
        })
        .catch(function (err) {
          cb.fail(err);
        });
    }
          
    // Ensure the Virtual Space is all loaded when this happens
    if (!that.$virtualSpace) {
      try {
        initCb = new Callback(baja.ok, baja.fail);    
       
        // Create the Virtual Space and initialize it
        that.$virtualSpace = new VirtualComponentSpace(that);
        that.$initPromise = that.$virtualSpace.init(initCb.getBatch());
        
        initCb.getBatch().addCallback({
          ok: callSuperLoadSlots,
          fail: function (err) {
            cb.fail(err);
          }
        });

        initCb.commit();
      } catch (err) {
        cb.fail(err);
      }
    } else {
      callSuperLoadSlots();
    }
    
    return cb.promise();
  };
  
  /**
   * Access the Nav Children.
   * 
   * @see baja.Component#getNavChildren
   */
  VirtualGateway.prototype.getNavChildren = function (obj) {
    // Access the Nav Children of the Virtual Space
    var space = this.getVirtualSpace();
    
    if (space) {
      return space.getRootComponent().getNavChildren(obj);
    }
    
    return callSuper("getNavChildren", VirtualGateway, this, arguments);
  };
  
  return VirtualGateway;
});