(function () {
  /**
   * Class responsible for all callbacks after any change in model
   * @param {MindMup} ysy
   * @constructor
   */
  function AfterChange(ysy) {
    this.ysy = ysy;
    this.init();
  }

  AfterChange.prototype.init = function () {
    var self = this;
    var executeByEvent = function (method, args) {
      if (!self[method]) return;
      return self[method].apply(self, args);
    };
    this.ysy.eventBus.register("TreeLoaded", /** @param {RootIdea} idea*/function (idea) {
      idea.addEventListener('changed', function (method, args) {
        if (method === "batch") {
          if (args && args.length) {
            for (var i = 0; i < args.length; i++) {
              var arg = args[i];
              if (arg && arg.length) {
                executeByEvent(arg[0], arg.slice(1));
              }
            }
          }
        } else {
          executeByEvent(method, args);
        }
      }, 5);
    });
  };
  AfterChange.prototype.removeSubIdea = function (id) {
    var node = this.ysy.getLayoutNode(id);
    if (!node) return;
    var saver = this.ysy.saver;
    if (saver.deleteStack) {
      saver.deleteStack.push(new window.easyMindMupClasses.ModelEntity().extend(node));
    }
  };
  AfterChange.prototype.paste = function (parentIdeaId, jsonToPaste, newIdeaId) {
    this._upgradeToModelEntity(newIdeaId);
  };
  AfterChange.prototype.insertIntermediate = function (inFrontOfIdeaId, title, newIdeaId) {
    var idea = this._upgradeToModelEntity(newIdeaId);
    idea.attr.isFresh = true;
  };
  AfterChange.prototype.addSubIdea = function (parentId, ideaTitle, ideaId) {
    var idea = this._upgradeToModelEntity(ideaId);
    idea.attr.isFresh = true;
  };
  /**
   * Function, which converts Object generated by MindMup component into ModelEntity
   * @param {number} ideaId
   * @private
   */
  AfterChange.prototype._upgradeToModelEntity = function (ideaId) {
    /** @type {MindMup} */
    var ysy = this.ysy;
    // var rootIdea = ysy.idea;
    var idea = ysy.util.findWhere(ysy.idea, function (/** @type {ModelEntity} */ node) {
      return node.id === ideaId;
    });
    return ysy.upgradeToModelEntity(idea);
  };

  window.easyMindMupClasses.AfterChange = AfterChange;
})();
