baja/tag/SmartRelations.js

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

/**
 * @module baja/tag/SmartRelation
 */
define([], function () {
  
  "use strict";
     
  /**
   * SmartRelations holds a collection of both direct and implemented
   * {@link module:baja/tag/Relation} objects.
   *
   * @class
   * @alias module:baja/tag/SmartRelation
   *
   * @param directRelations A direct Relations implementation.
   * @param impliedRelations An implied Relations implementation.
   */  
  var SmartRelations = function SmartRelations(directRelations, impliedRelations) {
    this.$directRelations = directRelations;
    this.$impliedRelations = impliedRelations;
  };

  /**
   * @returns {Boolean} Returns true if there are no Relation objects.
   */
  SmartRelations.prototype.isEmpty = function () {
    return this.$directRelations.isEmpty() && this.$impliedRelations.isEmpty();
  };

  /**
   * Find the specified Relation object via its Id and return it.
   * If the Relation can't be found then return null.
   * 
   * @param  {String|module:baja/tag/Id} id The Id
   * used for the search. This can be an Id or a qname for an Id.
   * @param {String|baja.Ord} [entityOrd] The Entity ORD we're looking for.
   * If this isn't defined, the first matching relation with specified tag is 
   * returned.
   * @returns {module:baja/tag/Relation} The Relation object
   * or null if nothing can be found.
   */
  SmartRelations.prototype.get = function (id, entityOrd) {
    return (this.$directRelations.get(id, entityOrd) || this.$impliedRelations.get(id, entityOrd)) || null;
  };

  /**
   * Returns a copy of the contained Relations array.
   *
   * Any duplicate relations are filtered out.
   * 
   * @returns {Array<module:baja/tag/Relation>} An array of Relation objects.
   */
  SmartRelations.prototype.getAll = function () {
    var relations = this.$impliedRelations.getAll(),
        directRelations = this.$directRelations.getAll(),
        i;

    for (i = 0; i < directRelations.length; ++i) {
      if (!this.$impliedRelations.get(directRelations[i].getId())) {
        relations.push(directRelations[i]);
      }
    }

    return relations;
  };

  /**
   * Return the direct relations.
   * 
   * @returns The direct Relations.
   */
  SmartRelations.prototype.getDirectRelations = function () {
    return this.$directRelations;
  };

  /**
   * Return the implied relations.
   * 
   * @returns the implied relations.
   */
  SmartRelations.prototype.getImpliedRelations = function () {
    return this.$impliedRelations;
  };

  return SmartRelations;
});