Source: models/Node.js

require('../polyfill');

/**
 * Mixin type that allows path items (Depot, Dir, and File) to operate like a
 * tree easily.
 *
 * A node requires that the implementing class provide certain basic properties:
 *
 * 1. `this.children`: If the node contains children, this should be defined as an
 *    empty array.
 *
 * 2. `this.pathId`: This should be an array of path names indicating the
 *    absolute location in an easily comparable way.
 *
 * 3. `this.name`: The comparable string 'name' of the item
 *
 * @mixin
 */
var Node = {

  /**
   *
   */
  sortChildren: function() {
    this.children.sort(function(a, b) { return a.name.localeCompare(b.name); });
  },

  /**
   * Inserts the child into the tree, if it belongs.
   *
   * @param child
   * @return {boolean} Returns true if the child is inserted
   */
  insert: function (child) {
    if (!this.children) {
      return false;
    }

    if (child.isChildRelation(this)) {
      this.children.push(child);
      return true;
    }

    for (var index = 0; index < this.children.length; index++) {
      if (this.children[index].insert(child)) {
        return true;
      }
    }

    return false;
  },

  /**
   * Validates that the current node could be a child of the indicated parent.
   *
   * @param parent The potential parent
   */
  isChildRelation: function (parent) {
    return (this.pathId.length == (parent.pathId.length + 1)) &&
      (this.getParentName() == parent.name);
  },

  /**
   * Returns the parent name of this node.
   *
   * @return {string}
   */
  getParentName: function () {
    if (this.pathId.length > 1) {
      return this.pathId[this.pathId.length - 2];
    }
    return undefined;
  }
};

module.exports = Node;