// Generated by CoffeeScript 1.12.7
var BaseMigration, MigrateSkipException,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

BaseMigration = (function(superClass) {
  extend(BaseMigration, superClass);

  function BaseMigration() {
    return BaseMigration.__super__.constructor.apply(this, arguments);
  }

  BaseMigration.click = function() {
    var baseMigration;
    ez5.rootMenu.closeMenu();
    baseMigration = new BaseMigration();
    return baseMigration.showDownloadUploadModal();
  };

  BaseMigration.label = function() {
    return "base.migration.button";
  };

  BaseMigration.is_allowed = function() {
    return ez5.session.hasSystemRight("root", "plugin.basemigration.migration");
  };

  BaseMigration.group = function() {
    return "za_other";
  };

  BaseMigration.submenu = function() {
    return "plugins";
  };

  BaseMigration.prototype.log = function(txt) {
    var arg, args, i, len;
    console.debug.apply(console, arguments);
    args = [];
    for (i = 0, len = arguments.length; i < len; i++) {
      arg = arguments[i];
      args.push(arg);
    }
    return this.__console.log(args.join(" "));
  };

  BaseMigration.prototype.showDownloadUploadModal = function() {
    var diag, downloadBtn, fileReader, uploadBtn;
    this.__console = new CUI.Console();
    fileReader = new CUI.FileReader({
      onAdd: (function(_this) {
        return function() {
          return uploadBtn.startSpinner();
        };
      })(this),
      onFail: (function(_this) {
        return function() {
          uploadBtn.stopSpinner();
          return CUI.alert({
            text: $$("base.migration.error.file_upload_failed")
          });
        };
      })(this),
      onDone: (function(_this) {
        return function(frf) {
          var e, uploaded_data;
          uploadBtn.stopSpinner();
          try {
            uploaded_data = JSON.parse(frf.getResult());
            if (uploaded_data.dump_version !== BaseMigration.dumpVersion) {
              CUI.alert({
                text: $$("base.migration.dump_version_not_matching", {
                  version_found: uploaded_data.dump_version || "unknown",
                  version_expected: BaseMigration.dumpVersion
                })
              });
              return;
            }
          } catch (error) {
            e = error;
            CUI.alert({
              text: $$("base.migration.unable_to_parse_file")
            });
            return;
          }
          _this.log($$("base.migration.console.log.filename.md", {
            filename: frf.getFile().name,
            filesize: ez5.format_filesize(frf.getFile().size)
          }));
          diag.destroy();
          _this.presentUploadedData(uploaded_data);
        };
      })(this)
    });
    downloadBtn = new LocaButton({
      loca_key: "base.migration.choice.download",
      disabled: true,
      onClick: (function(_this) {
        return function(ev, btn) {
          _this["export"]();
          return diag.destroy();
        };
      })(this)
    });
    if (ez5.session.isReadOnly()) {
      uploadBtn = new CUI.Button({
        text: $$("base.migration.choice.upload|text"),
        icon: $$("base.migration.choice.upload|icon"),
        disabled: true,
        onClick: (function(_this) {
          return function() {
            console.debug("Upload button clicked in read-only mode");
            return CUI.problem({
              text: $$("base.error.user.read_only_mode")
            });
          };
        })(this)
      });
    } else {
      uploadBtn = new CUI.FileUploadButton({
        fileUpload: fileReader,
        text: $$("base.migration.choice.upload|text"),
        disabled: true,
        multiple: false,
        icon: $$("base.migration.choice.upload|icon")
      });
    }
    diag = new CUI.ConfirmationDialog({
      cancel: true,
      title: $$("base.migration.choice.title"),
      size: "xs",
      "class": "ez5-base-migration-download-upload-modal",
      content: new LocaLabel({
        loca_key: "base.migration.choice.loading"
      }),
      buttons: [downloadBtn, uploadBtn]
    }).show();
    return this.loadBaseData().done((function(_this) {
      return function() {
        _this.log($$("base.migration.console.log.base-data-loaded"));
        if (diag.isDestroyed()) {
          return;
        }
        downloadBtn.enable();
        uploadBtn.enable();
        diag.setText($$("base.migration.choice.info"));
        return diag.autoSize();
      };
    })(this));
  };

  BaseMigration.prototype.getBaseData = function() {
    return this.__baseData;
  };

  BaseMigration.prototype.migrateWhoInData = function(data, where, level) {
    var e, idx, item, key, ref, ret, value;
    if (where == null) {
      where = "";
    }
    if (level == null) {
      level = 0;
    }
    if ((ref = data != null ? data._basetype : void 0) === "group" || ref === "user") {
      try {
        return this.migrateWho(data);
      } catch (error) {
        e = error;
        if (e instanceof MigrateSkipException) {
          this.log($$("base.migration.console.log.where-skipping-who", {
            where: where,
            error: e.getError()
          }));
        }
        throw e;
      }
      return null;
    }
    if (CUI.isArray(data)) {
      idx = 0;
      while (data.length > idx) {
        item = data[idx];
        try {
          ret = this.migrateWhoInData(item, where, level + 1);
          if (ret !== null) {
            data[idx] = ret;
          }
        } catch (error) {
          e = error;
          if (e instanceof MigrateSkipException) {
            data.splice(idx, 1);
            continue;
          }
          throw e;
        }
        idx++;
      }
      return null;
    }
    if (CUI.isPlainObject(data)) {
      for (key in data) {
        value = data[key];
        try {
          ret = this.migrateWhoInData(value, where, level + 1);
          if (ret !== null) {
            data[key] = ret;
          }
        } catch (error) {
          e = error;
          if (e instanceof MigrateSkipException) {
            delete data[key];
            continue;
          }
          throw e;
        }
      }
      return null;
    }
    return null;
  };

  BaseMigration.prototype.migrateTransition = function(transition) {
    var copied_transition, e, i, j, k, l, len, len1, len2, new_tagfilter, new_who, ref, ref1, ref2, who;
    copied_transition = {
      who: []
    };
    ref = ["actions", "comment", "confirm", "objecttype_ids", "operations", "sticky", "type"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      copied_transition[k] = CUI.util.copyObject(transition[k], true);
    }
    ref1 = ["tagfilter:before", "tagfilter:after"];
    for (j = 0, len1 = ref1.length; j < len1; j++) {
      k = ref1[j];
      if (!transition[k]) {
        continue;
      }
      try {
        new_tagfilter = this.migrateTagFilter(transition[k]);
      } catch (error) {
        e = error;
        if (e instanceof MigrateSkipException) {
          this.log($$("base.migration.console.log.skipping-tag-filter"), {
            error: e.getError()
          });
          new_tagfilter = null;
        } else {
          throw e;
        }
      }
      if (new_tagfilter) {
        copied_transition[k] = new_tagfilter;
      }
    }
    ref2 = transition.who;
    for (l = 0, len2 = ref2.length; l < len2; l++) {
      who = ref2[l];
      try {
        new_who = this.migrateWho(who);
      } catch (error) {
        e = error;
        if (e instanceof MigrateSkipException) {
          this.log($$("base.migration.console.log.skipping-who", {
            error: e.getError()
          }));
          new_who = null;
        } else {
          throw e;
        }
      }
      if (new_who) {
        copied_transition.who.push(new_who);
      }
    }
    if (ez5.version("6")) {
      copied_transition.who_not = transition.who_not || false;
    }
    if (copied_transition.actions) {
      this.migrateWhoInData(copied_transition.actions, "Transition: Actions");
    }
    if (copied_transition.who.length === 0) {
      this.log($$("base.migration.console.log.transition.no-migratable-found.md"));
      console.warn($$("base.migration.console.log.transition.no-migratable-found.md"), transition);
      return void 0;
    }
    return copied_transition;
  };

  BaseMigration.prototype.migrateACL = function(acl) {
    var acl_row, copied_rights, e, i, len;
    copied_rights = [];
    for (i = 0, len = acl.length; i < len; i++) {
      acl_row = acl[i];
      try {
        copied_rights.push(this.migrateACLRow(acl_row));
      } catch (error) {
        e = error;
        if (e instanceof MigrateSkipException) {
          this.log($$("base.migration.console.log.skipping-right", {
            error: e.getError()
          }));
        } else {
          throw e;
        }
      }
    }
    return copied_rights;
  };

  BaseMigration.prototype.migrateACLRow = function(right) {
    var new_right;
    new_right = {
      active: right.active,
      rights: this.migrateRights(right.rights),
      who: this.migrateWho(right.who)
    };
    if (right.tagfilter) {
      new_right.tagfilter = this.migrateTagFilter(right.tagfilter);
    }
    return new_right;
  };

  BaseMigration.prototype.migrateTagFilter = function(tagfilter) {
    var i, j, k, len, len1, new_tagfilter, ref, ref1, tag_id;
    new_tagfilter = {};
    ref = ["all", "any", "not", "changed"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      if (!tagfilter[k]) {
        continue;
      }
      if (!new_tagfilter[k]) {
        new_tagfilter[k] = [];
      }
      ref1 = tagfilter[k];
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        tag_id = ref1[j];
        new_tagfilter[k].push(this.migrateTagID(tag_id));
      }
    }
    if (CUI.isEmptyObject(new_tagfilter)) {
      return void 0;
    } else {
      return new_tagfilter;
    }
  };

  BaseMigration.prototype.migrateTagID = function(tag_id) {
    var i, len, ref, source_tag, tag;
    source_tag = this.__sourceData._tag_by_id[tag_id];
    ref = this.__baseData._tags;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      if (tag._tag_identifier === source_tag._tag_identifier) {
        return tag.tag._id;
      }
    }
    throw new MigrateSkipException({
      text: $$("base.migration.exception.tag-not-found.text.md", {
        target: source_tag._tag_identifier
      })
    });
  };

  BaseMigration.prototype.migrateRights = function(rights) {
    return CUI.util.copyObject(rights, true);
  };

  BaseMigration.prototype.migrateWho = function(who) {
    var _who, baseType, baseUser, dn, errorText, group, groups, new_who, ref, ref1, ref2, ref3, sourceUserReference;
    if (ez5.version("6")) {
      if (who.group) {
        group = this.__sourceData.group.find((function(_this) {
          return function(sourceGroup) {
            return sourceGroup.group._id === who.group._id;
          };
        })(this));
        if (group) {
          who.group = group.group;
        }
      }
    }
    _who = AclWho.newInstance(who);
    baseType = who._basetype;
    dn = _who.getDisplayText();
    if (baseType === "group") {
      groups = this.findGroupsByGroup(who);
      if (groups.length === 0) {
        throw new MigrateSkipException({
          text: $$("base.migration.exception.group-not-found.text.md", {
            group: dn
          })
        });
      } else if (groups.length > 1) {
        console.warn("Who:", who, groups);
        throw new MigrateSkipException({
          text: $$("base.migration.exception.group-repeat.text.md", {
            group: dn
          })
        });
      }
      new_who = {
        _basetype: "group",
        group: {
          _id: groups[0].group._id,
          name: groups[0].group.name,
          displayname: groups[0].group.displayname
        }
      };
    } else if (baseType === "user" && ez5.version("6")) {
      sourceUserReference = (ref = this.getSourceData()["user"]) != null ? (ref1 = ref.find((function(_this) {
        return function(source_user) {
          return source_user.user._id === who.user._id;
        };
      })(this))) != null ? (ref2 = ref1.user) != null ? ref2.reference : void 0 : void 0 : void 0;
      if (!sourceUserReference) {
        throw new MigrateSkipException({
          text: $$("base.migration.exception.user-not-found.text.md", {
            user: dn
          })
        });
      }
      baseUser = (ref3 = this.getBaseData()["user"]) != null ? ref3.find((function(_this) {
        return function(base_user) {
          return base_user.user.reference === sourceUserReference;
        };
      })(this)) : void 0;
      if (!baseUser) {
        throw new MigrateSkipException({
          text: $$("base.migration.exception.user-not-found.text.md", {
            user: dn
          })
        });
      }
      new_who = {
        _basetype: "user",
        user: {
          _id: baseUser.user._id,
          reference: baseUser.user.reference
        }
      };
    } else {
      errorText = $$("base.migration.exception.basetype-not-group.text.md", {
        baseType: baseType,
        displayText: CUI.MarkdownInput.escape(dn)
      });
      throw new MigrateSkipException({
        text: errorText
      });
    }
    return new_who;
  };

  BaseMigration.prototype.findGroupsByGroup = function(group_data) {
    var found_groups, group, i, len, ref;
    found_groups = [];
    ref = this.__baseData.group;
    for (i = 0, len = ref.length; i < len; i++) {
      group = ref[i];
      if (group.group.type !== group_data.group.type) {
        continue;
      }
      switch (group.group.type) {
        case "system":
          if ((!ez5.version("6") && group.group.name === group_data.group.name) || (ez5.version("6") && group.group.reference === group_data.group.reference)) {
            found_groups.push(group);
          }
          break;
        case "easydb":
          if (ez5.loca.getBestFrontendValue(group.group.displayname) === ez5.loca.getBestFrontendValue(group_data.group.displayname)) {
            found_groups.push(group);
          }
      }
    }
    return found_groups;
  };

  BaseMigration.prototype.enhanceBaseData = function(baseData) {
    var context, contexts, i, info, j, l, len, len1, len2, len3, m, preset, ref, ref1, ref2, ref3, rights, tag, tag_group_name, taggroup, user, userList;
    baseData._tags = [];
    baseData._utf8_test = "äöüÄÖÜß";
    baseData._tag_by_id = {};
    ref = baseData.tags;
    for (i = 0, len = ref.length; i < len; i++) {
      taggroup = ref[i];
      tag_group_name = ez5.loca.getBestFrontendValue(taggroup.taggroup.displayname);
      ref1 = taggroup._tags;
      for (j = 0, len1 = ref1.length; j < len1; j++) {
        tag = ref1[j];
        tag._tag_identifier = tag_group_name + "." + ez5.loca.getBestFrontendValue(tag.tag.displayname);
        baseData._tags.push(tag);
        baseData._tag_by_id[tag.tag._id] = tag;
      }
    }
    if (baseData.right && !baseData.preset) {
      rights = {};
      contexts = baseData.right;
      for (context in contexts) {
        info = contexts[context];
        if (!info.capabilities.preset || !info.presets) {
          continue;
        }
        rights[context] = [];
        ref2 = info.presets;
        for (l = 0, len2 = ref2.length; l < len2; l++) {
          preset = ref2[l];
          rights[context].push(preset);
        }
      }
      baseData.preset = rights;
      delete baseData.right;
    }
    if (baseData["user"] != null) {
      userList = [];
      ref3 = baseData.user;
      for (m = 0, len3 = ref3.length; m < len3; m++) {
        user = ref3[m];
        if (user.user.reference != null) {
          userList.push({
            basetype: "user",
            user: {
              _id: user.user._id,
              reference: user.user.reference
            }
          });
        }
      }
      baseData.user = userList;
      console.log("BaseMigration: Enhanced user data, only reference and id are kept for migration purposes.", baseData.user);
    }
    return this;
  };

  BaseMigration.prototype.loadBaseData = function() {
    var base_data, dfr, fn, i, len, promises, type, types;
    base_data = {
      dump_version: BaseMigration.dumpVersion
    };
    promises = [];
    types = ["tags", "transitions", "pool", "config", "objecttype", "group", "right", "user"];
    fn = (function(_this) {
      return function(type) {
        return promises.push(ez5.api[type]().done(function(data) {
          return base_data[type] = data;
        }));
      };
    })(this);
    for (i = 0, len = types.length; i < len; i++) {
      type = types[i];
      fn(type);
    }
    dfr = new CUI.Deferred();
    CUI.when(promises).done((function(_this) {
      return function() {
        _this.enhanceBaseData(base_data);
        _this.__baseData = base_data;
        return dfr.resolve();
      };
    })(this)).fail((function(_this) {
      return function() {
        return CUI.alert({
          text: $$("base.migration.error.load_base_data_failed")
        });
      };
    })(this));
    return dfr.promise();
  };

  BaseMigration.prototype["export"] = function() {
    var baseData, i, inst, k, len, name, ref;
    name = [];
    inst = ez5.session.getInstance();
    ref = ["name"];
    for (i = 0, len = ref.length; i < len; i++) {
      k = ref[i];
      name.push(inst[k]);
    }
    baseData = this.getBaseData();
    return CUI.downloadData(JSON.stringify(baseData), ez5.session.getEasydbName() + "_Permissions_" + CUI.util.moment().format('YYYY-MM-DD') + ".json");
  };

  BaseMigration.prototype.getSourceData = function() {
    return this.__sourceData;
  };

  BaseMigration.prototype.getConsole = function() {
    return new CUI.SimplePane({
      header_left: new CUI.Label({
        text: $$("base.migration.console.text")
      }),
      header_right: {
        icon: $$("base.migration.console.icon"),
        onClick: (function(_this) {
          return function() {
            return _this.__console.clear();
          };
        })(this)
      },
      content: this.__console
    });
  };

  BaseMigration.prototype.presentUploadedData = function(__sourceData) {
    var i, k, len, migrate_key, migrate_keys, mod, ref, ref1, source_nodes, source_tree, v;
    this.__sourceData = __sourceData;
    this.enhanceBaseData(this.__sourceData);
    source_nodes = [];
    migrate_keys = ["config", "group", "tags", "transitions", "objecttype", "pool", "dump_version", "_utf8_test", "preset"];
    ref = this.__sourceData;
    for (k in ref) {
      v = ref[k];
      if (!k.startsWith("_") && indexOf.call(migrate_keys, k) < 0) {
        this.log($$("base.migration.console.log.skipping-unsupported-data"), k, v.length, v);
      }
    }
    for (i = 0, len = migrate_keys.length; i < len; i++) {
      migrate_key = migrate_keys[i];
      ref1 = this.__sourceData;
      for (k in ref1) {
        v = ref1[k];
        if (k !== migrate_key) {
          continue;
        }
        switch (k) {
          case "pool":
            source_nodes.push.apply(source_nodes, BaseMigrationNodePool.getSourceNodesFromData(this, v));
            break;
          case "objecttype":
            source_nodes.push.apply(source_nodes, BaseMigrationNodeObjecttype.getSourceNodesFromData(this, v));
            break;
          case "tags":
            source_nodes.push.apply(source_nodes, BaseMigrationNodeTagGroup.getSourceNodesFromData(this, v));
            break;
          case "group":
            source_nodes.push.apply(source_nodes, BaseMigrationNodeGroup.getSourceNodesFromData(this, v));
            break;
          case "transitions":
            source_nodes.push.apply(source_nodes, BaseMigrationNodeTransition.getSourceNodesFromData(this, v));
            break;
          case "preset":
            source_nodes.push.apply(source_nodes, BaseMigrationNodePreset.getSourceNodesFromData(this, v));
            break;
          case "dump_version":
            console.info("Dump Version:", v);
            break;
          case "_utf8_test":
            console.info("Utf8-Test:", v);
        }
      }
    }
    source_tree = new CUI.ListViewTree({
      cols: ["maximize"],
      selectableRows: true,
      header_left: new CUI.Label({
        text: $$("base.migration.source-tree.header.text")
      }),
      onSelect: (function(_this) {
        return function(ev, info) {
          var actionPane;
          actionPane = info.node.getActionPane();
          return _this.__layout.replace(actionPane, "center");
        };
      })(this),
      onDeselect: (function(_this) {
        return function(ev, info) {
          return _this.__layout.replace(_this.getEmptyPane(), "center");
        };
      })(this),
      children: source_nodes
    });
    this.__layout = new CUI.HorizontalLayout({
      left: {
        "class": "ez5-base-migration-tree",
        content: source_tree.render(),
        flexHandle: {
          hidden: false,
          state_name: "base-migration-tree"
        }
      },
      center: {
        "class": "ez5-base-migration-content",
        content: this.getEmptyPane()
      },
      right: {
        "class": "ez5-base-migration-console",
        flexHandle: {
          hidden: false,
          state_name: "base-migration-console"
        },
        content: this.getConsole()
      }
    });
    mod = new CUI.Modal({
      "class": "ez5-base-migration-modal",
      cancel: true,
      fill_space: "both",
      onHide: (function(_this) {
        return function() {
          return delete _this.__baseData;
        };
      })(this),
      pane: {
        header_left: new CUI.Label({
          text: $$("base.migration.choice.title")
        }),
        content: this.__layout,
        footer_right: new LocaButton({
          loca_key: "base.migration.migration.button.done",
          secondary: true,
          onClick: (function(_this) {
            return function() {
              return mod.destroy();
            };
          })(this)
        })
      }
    }).show();
    return source_tree.root.open();
  };

  BaseMigration.prototype.getEmptyPane = function() {
    return new CUI.EmptyLabel({
      centered: true,
      multiline: true,
      markdown: true,
      text: $$("base.migration.empty-pane.text.md")
    });
  };

  BaseMigration.dumpVersion = 1;

  return BaseMigration;

})(RootMenuApp);

MigrateSkipException = (function(superClass) {
  extend(MigrateSkipException, superClass);

  function MigrateSkipException() {
    return MigrateSkipException.__super__.constructor.apply(this, arguments);
  }

  return MigrateSkipException;

})(UserError);

ez5.session_ready(function() {
  return ez5.rootMenu.registerApp(BaseMigration);
});
// Generated by CoffeeScript 1.12.7
var BaseMigrationNode,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNode = (function(superClass) {
  extend(BaseMigrationNode, superClass);

  function BaseMigrationNode() {
    return BaseMigrationNode.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNode.prototype.initOpts = function() {
    BaseMigrationNode.__super__.initOpts.call(this);
    return this.addOpts({
      migration: {
        mandatory: true,
        check: BaseMigration
      }
    });
  };

  BaseMigrationNode.prototype.getActionPane = function() {
    return new CUI.EmptyLabel({
      centered: true,
      multiline: true,
      text: $$("base.migration.action_pane." + CUI.util.getObjectClass(this))
    });
  };

  BaseMigrationNode.prototype.getDisplayText = function() {
    return "<data-node>";
  };

  BaseMigrationNode.prototype.log = function() {
    return this._migration.log.apply(this._migration, arguments);
  };

  BaseMigrationNode.prototype.getMigration = function() {
    return this._migration;
  };

  return BaseMigrationNode;

})(CUI.ListViewTreeNode);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeStructure,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeStructure = (function(superClass) {
  extend(BaseMigrationNodeStructure, superClass);

  function BaseMigrationNodeStructure() {
    return BaseMigrationNodeStructure.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeStructure.prototype.initOpts = function() {
    BaseMigrationNodeStructure.__super__.initOpts.call(this);
    return this.addOpts({
      name: {
        mandatory: true,
        check: String
      }
    });
  };

  BaseMigrationNodeStructure.prototype.renderContent = function() {
    return new CUI.Label({
      text: this._name
    });
  };

  return BaseMigrationNodeStructure;

})(BaseMigrationNode);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeData,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeData = (function(superClass) {
  extend(BaseMigrationNodeData, superClass);

  function BaseMigrationNodeData() {
    return BaseMigrationNodeData.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeData.prototype.initOpts = function() {
    BaseMigrationNodeData.__super__.initOpts.call(this);
    return this.addOpts({
      data: {
        mandatory: true,
        "default": {},
        check: "PlainObject"
      }
    });
  };

  BaseMigrationNodeData.prototype.readOpts = function() {
    BaseMigrationNodeData.__super__.readOpts.call(this);
    return this.setData(this._data);
  };

  BaseMigrationNodeData.prototype.hasRightPane = function() {
    return false;
  };

  BaseMigrationNodeData.prototype.getActionPaneBase = function() {
    var fields, right_pane;
    this.__actionData = {
      mode: "replace"
    };
    fields = this.getActionFields();
    if (this.hasRightPane()) {
      right_pane = {
        "class": "ez5-base-migration-center-right",
        flexHandle: {
          hidden: false,
          closed: false,
          state_name: "base-migration-right"
        }
      };
    } else {
      right_pane = void 0;
    }
    this.__layout = new CUI.HorizontalLayout({
      center: {
        "class": "ez5-base-migration-center-center",
        content: (function(_this) {
          return function() {
            return new CUI.Form({
              padded: true,
              data: _this.__actionData,
              fields: fields,
              onDataChanged: function() {
                return _this.checkMigrateButton();
              }
            }).start();
          };
        })(this)
      },
      right: right_pane
    });
    this.__migrateBtn = new LocaButton({
      loca_key: "base.migration.node.pool.button.migrate",
      primary: true,
      disabled: true,
      onClick: (function(_this) {
        return function(ev, btn) {
          btn.startSpinner();
          return _this.migrate(ev, _this.__actionData).always(function() {
            return btn.stopSpinner();
          }).done(function() {
            if (ev.hasModifierKey()) {
              return;
            }
            return _this.getMigration().loadBaseData().done(function() {
              return CUI.alert({
                text: $$("base.migration.node.pool.success.text")
              });
            });
          }).fail(function() {
            if (ev.hasModifierKey()) {
              return;
            }
            return CUI.problem({
              text: $$("base.migration.node.pool.error.text")
            });
          });
        };
      })(this)
    });
    this.checkMigrateButton();
    return new CUI.SimplePane({
      header_left: new CUI.Label({
        text: $$("base.migration.node.pool.pane.text")
      }),
      content: this.__layout,
      footer_right: [this.__migrateBtn]
    });
  };

  BaseMigrationNodeData.prototype.getLayout = function() {
    return this.__layout;
  };

  BaseMigrationNodeData.prototype.setData = function(__data) {
    this.__data = __data;
  };

  BaseMigrationNodeData.prototype.getData = function() {
    return this.__data;
  };

  BaseMigrationNodeData.prototype.renderContent = function() {
    return new CUI.Label({
      multiline: true,
      text: this.getDisplayText()
    });
  };

  return BaseMigrationNodeData;

})(BaseMigrationNode);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeObjecttypes,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeObjecttypes = (function(superClass) {
  extend(BaseMigrationNodeObjecttypes, superClass);

  function BaseMigrationNodeObjecttypes() {
    return BaseMigrationNodeObjecttypes.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeObjecttypes.prototype.getDisplayText = function() {
    return $$("base.migration.node.objecttype.text");
  };

  BaseMigrationNodeObjecttypes.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeObjecttypes.prototype.getActionFields = function() {
    var acl, c, columnFilters, data, i, len, name, ref;
    acl = [];
    columnFilters = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      data = c.getData();
      name = c.getDisplayText();
      if (data._acl.length > 0) {
        acl.push(name + " (" + data._acl.length + ")");
      }
      if (data._columnfilters.length > 0) {
        columnFilters.push(name + " (" + data._columnfilters.length + ")");
      }
    }
    return [
      {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.node.objecttypes.permissions.label")
        },
        options: [
          {
            text: acl.length !== 0 ? acl.join(", ") : $$("base.migration.node.objecttype.empty-selection"),
            disabled: acl.length === 0,
            value: "acl"
          }
        ]
      }, {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.node.objecttypes.columnfilters.label")
        },
        options: [
          {
            text: columnFilters.length !== 0 ? columnFilters.join(", ") : $$("base.migration.node.objecttype.empty-selection"),
            disabled: columnFilters.length === 0,
            value: "columnfilters"
          }
        ]
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.node.objecttype.mode.label")
        },
        options: [
          {
            text: $$("base.migration.node.objecttype.mode.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.node.objecttype.mode.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodeObjecttypes.prototype.checkMigrateButton = function() {
    this.__migrateBtn.disable();
    if (this.__actionData.migrate.length === 0) {
      return;
    }
    this.__migrateBtn.enable();
  };

  BaseMigrationNodeObjecttypes.prototype.migrate = function(ev, action_data) {
    var dfr, idx, next_ot_node;
    dfr = new CUI.Deferred();
    idx = 0;
    next_ot_node = (function(_this) {
      return function() {
        var ot_node, ret;
        if (idx === _this.children.length) {
          dfr.resolve();
          return;
        }
        ot_node = _this.children[idx];
        ret = ot_node.migrate(ev, action_data);
        return ret.done(function() {
          idx++;
          return next_ot_node();
        }).fail(function() {
          return dfr.reject();
        });
      };
    })(this);
    next_ot_node();
    return dfr.promise();
  };

  return BaseMigrationNodeObjecttypes;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeObjecttype,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

BaseMigrationNodeObjecttype = (function(superClass) {
  extend(BaseMigrationNodeObjecttype, superClass);

  function BaseMigrationNodeObjecttype() {
    return BaseMigrationNodeObjecttype.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeObjecttype.prototype.readOpts = function() {
    var i, idx, len, ot, ref;
    BaseMigrationNodeObjecttype.__super__.readOpts.call(this);
    this.__target_objecttype = null;
    ref = this.getMigration().getBaseData().objecttype;
    for (idx = i = 0, len = ref.length; i < len; idx = ++i) {
      ot = ref[idx];
      if (ot.objecttype.name === this.getData().objecttype.name) {
        ot._idx_in_base_data = idx;
        this.__target_objecttype = ot;
        break;
      }
    }
  };

  BaseMigrationNodeObjecttype.prototype.getTargetObjecttype = function() {
    return this.__target_objecttype;
  };

  BaseMigrationNodeObjecttype.prototype.getDisplayText = function() {
    return this.getData().objecttype.name;
  };

  BaseMigrationNodeObjecttype.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeObjecttype.prototype.getActionFields = function() {
    var ref, ref1;
    return [
      {
        type: CUI.Output,
        form: {
          label: $$("base.migration.node.objecttype.objecttype.label")
        },
        text: this.getDisplayText()
      }, {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.node.objecttype.migrate.label")
        },
        options: [
          {
            text: $$("base.migration.node.objecttype.migrate.check_acl", {
              acl_count: (ref = this.getData()._acl) != null ? ref.length : void 0
            }),
            disabled: ((ref1 = this.getData()._acl) != null ? ref1.length : void 0) === 0,
            value: "acl"
          }, {
            text: $$("base.migration.node.objecttype.migrate.columnfilters", {
              acl_count: this.getData()._columnfilters.length
            }),
            disabled: this.getData()._columnfilters.length === 0,
            value: "columnfilters"
          }
        ]
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$('base.migration.node.objecttype.mode.label')
        },
        options: [
          {
            text: $$('base.migration.node.objecttype.mode.replace'),
            value: "replace"
          }, {
            text: $$('base.migration.node.objecttype.mode.add'),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodeObjecttype.prototype.migrate = function(ev, action_data) {
    var _acl, acl, cf, do_save, i, j, len, len1, migration, new_acl, new_cf, new_columnfilters, ref, ref1, ref2, ref3, save_ot, source_ot, target_ot, who;
    console.debug("migrate Objecttype:", this.getDisplayText());
    source_ot = this.getData();
    target_ot = this.getTargetObjecttype();
    migration = this.getMigration();
    if (!target_ot) {
      this.log($$("base.migration.console.log.objecttype.target-not-found.md", {
        name: source_ot.objecttype.name
      }));
      return CUI.resolvedPromise();
    }
    save_ot = {
      _basetype: "objecttype",
      objecttype: {
        _id: target_ot.objecttype._id,
        _version: target_ot.objecttype._version + 1
      }
    };
    do_save = false;
    if (indexOf.call(action_data.migrate, "acl") >= 0) {
      new_acl = migration.migrateACL(source_ot._acl);
      if (new_acl.length > 0) {
        save_ot._acl = [];
        if (action_data.mode === "add") {
          save_ot._acl.push.apply(save_ot._acl, target_ot._acl);
        }
        save_ot._acl.push.apply(save_ot._acl, new_acl);
        do_save = true;
      }
    }
    if (indexOf.call(action_data.migrate, 'columnfilters') >= 0) {
      save_ot._columnfilters = [];
      new_columnfilters = [];
      ref = source_ot._columnfilters;
      for (i = 0, len = ref.length; i < len; i++) {
        cf = ref[i];
        new_cf = {
          internal_name: cf.internal_name,
          columns: cf.columns
        };
        if (cf.tagfilter) {
          new_cf.tagfilter = migration.migrateTagFilter(cf.tagfilter) || {};
        }
        acl = [];
        ref1 = cf.who || [];
        for (j = 0, len1 = ref1.length; j < len1; j++) {
          who = ref1[j];
          acl.push({
            who: who
          });
        }
        new_acl = migration.migrateACL(acl);
        if (new_acl.length > 0) {
          new_cf.who = (function() {
            var k, len2, results;
            results = [];
            for (k = 0, len2 = new_acl.length; k < len2; k++) {
              _acl = new_acl[k];
              results.push(_acl.who);
            }
            return results;
          })();
        }
        if (!((ref2 = cf.who) != null ? ref2.length : void 0) || ((ref3 = new_cf.who) != null ? ref3.length : void 0)) {
          new_columnfilters.push(new_cf);
        }
      }
      if (new_columnfilters.length > 0) {
        save_ot._columnfilters = [];
        if (action_data.mode === "add") {
          save_ot._columnfilters.push.apply(save_ot._columnfilters, target_ot._columnfilters);
        }
        save_ot._columnfilters.push.apply(save_ot._columnfilters, new_columnfilters);
        do_save = true;
      }
    }
    if (!do_save) {
      this.log($$("base.migration.console.log.objecttype.no-data-found.md"));
      return CUI.resolvedPromise();
    }
    if (ev.hasModifierKey()) {
      console.debug("objecttype save:", CUI.util.dump(save_ot));
      return CUI.resolvedPromise();
    }
    this.log($$("base.migration.console.log.objecttype.saving.md", {
      name: this.getDisplayText()
    }));
    return ez5.api.objecttype({
      type: "POST",
      json_data: [save_ot]
    }).done((function(_this) {
      return function(ot_data) {
        _this.log($$("base.migration.console.log.objecttype.migrated.md", {
          name: _this.getDisplayText(),
          count_acl: ot_data[0]._acl.length,
          count_columns: ot_data[0]._columnfilters.length
        }));
        return _this.getMigration().getBaseData().objecttype[target_ot._idx_in_base_data] = ot_data[0];
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.objecttype.failed.md", {
          name: _this.getDisplayText()
        }));
      };
    })(this));
  };

  BaseMigrationNodeObjecttype.prototype.checkMigrateButton = function() {
    this.__migrateBtn.disable();
    if (!this.getTargetObjecttype()) {
      return;
    }
    if (this.__actionData.migrate.length === 0) {
      return;
    }
    this.__migrateBtn.enable();
  };

  BaseMigrationNodeObjecttype.getSourceNodesFromData = function(migration, data) {
    var i, len, objecttype, objecttypes;
    objecttypes = [];
    for (i = 0, len = data.length; i < len; i++) {
      objecttype = data[i];
      objecttypes.push(new BaseMigrationNodeObjecttype({
        migration: migration,
        data: objecttype
      }));
    }
    objecttypes.sort((function(_this) {
      return function(a, b) {
        return CUI.util.compareIndex(a.getDisplayText(), b.getDisplayText());
      };
    })(this));
    return [
      new BaseMigrationNodeObjecttypes({
        migration: migration,
        children: objecttypes
      })
    ];
  };

  return BaseMigrationNodeObjecttype;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeTagGroups,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeTagGroups = (function(superClass) {
  extend(BaseMigrationNodeTagGroups, superClass);

  function BaseMigrationNodeTagGroups() {
    return BaseMigrationNodeTagGroups.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeTagGroups.prototype.getDisplayText = function() {
    return $$("base.migration.node.tag.text");
  };

  BaseMigrationNodeTagGroups.prototype.getActionFields = function() {
    var fields;
    fields = BaseMigrationNodeTagGroup.prototype.getActionFields.call(this);
    fields[0] = {
      type: CUI.Output,
      form: {
        label: $$("base.migration.node.tag_groups.text")
      },
      text: $$("base.migration.node.tag_groups.all.text")
    };
    return fields;
  };

  BaseMigrationNodeTagGroups.prototype.migrate = function(ev, action_data) {
    var c, i, len, new_target, ref, target;
    target = CUI.util.copyObject(this.getMigration().getBaseData().tags, true);
    console.debug("migrate all tag groups", ev, action_data);
    new_target = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      c.migrateTagGroup(target, action_data);
    }
    if (ev.hasModifierKey()) {
      console.debug("migrate TagGroups:", CUI.util.dump(target), target);
      return CUI.resolvedPromise();
    }
    return BaseMigrationNodeTagGroup.prototype.saveTags.call(this, target);
  };

  BaseMigrationNodeTagGroups.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  return BaseMigrationNodeTagGroups;

})(BaseMigrationNodeObjecttypes);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeTagGroup,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

BaseMigrationNodeTagGroup = (function(superClass) {
  extend(BaseMigrationNodeTagGroup, superClass);

  function BaseMigrationNodeTagGroup() {
    return BaseMigrationNodeTagGroup.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeTagGroup.prototype.readOpts = function() {
    var i, len, ref, tag;
    BaseMigrationNodeTagGroup.__super__.readOpts.call(this);
    this.children = [];
    ref = this.getData()._tags;
    for (i = 0, len = ref.length; i < len; i++) {
      tag = ref[i];
      this.children.push(new BaseMigrationNodeTag({
        migration: this._migration,
        data: tag
      }));
    }
  };

  BaseMigrationNodeTagGroup.prototype.getDisplayText = function() {
    return ez5.loca.getBestFrontendValue(this.getData().taggroup.displayname);
  };

  BaseMigrationNodeTagGroup.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeTagGroup.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Output,
        form: {
          label: $$("base.migration.node.tag.group.text")
        },
        text: this.getDisplayText()
      }, {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.common.selection")
        },
        options: [
          {
            text: $$("base.migration.node.tag.group.migrate_acl"),
            value: "acl"
          }
        ]
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodeTagGroup.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodeTagGroup.prototype.migrate = function(ev, action_data) {
    var target;
    target = CUI.util.copyObject(this.getMigration().getBaseData().tags, true);
    this.migrateTagGroup(target, action_data);
    if (ev.hasModifierKey()) {
      console.debug("migrate TagGroup:", CUI.util.dump(target), target);
      return CUI.resolvedPromise();
    }
    return this.saveTags(target);
  };

  BaseMigrationNodeTagGroup.prototype.saveTags = function(tags) {
    this.log($$("base.migration.console.log.tag.saving.md", {
      count: tags.length
    }));
    return ez5.api.tags({
      type: "POST",
      json_data: tags
    }).done((function(_this) {
      return function(tags) {
        var _tags, i, j, len, len1, ref, tag, taggroup;
        for (i = 0, len = tags.length; i < len; i++) {
          taggroup = tags[i];
          _tags = [];
          ref = taggroup._tags;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            tag = ref[j];
            _tags.push("**" + CUI.MarkdownInput.escape(ez5.loca.getBestFrontendValue(tag.tag.displayname)) + "**");
          }
          _this.log($$("base.migration.console.log.tag.migrated.md", {
            name: CUI.MarkdownInput.escape(ez5.loca.getBestFrontendValue(taggroup.taggroup.displayname)),
            tags: _tags.join(", ")
          }));
        }
        console.debug("updating base data:", tags);
        return _this.getMigration().getBaseData().tags = tags;
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.tag.failed"));
      };
    })(this));
  };

  BaseMigrationNodeTagGroup.prototype.migrateTagGroup = function(target, action_data) {
    var add, dn_source, find_tags, i, idx, j, k, l, len, len1, len2, len3, len4, len5, m, migration, n, newTags, new_acl, new_tag, new_taggroup, ref, ref1, ref2, ref3, ref4, source_tag, source_tg, tag, target_tags, tg;
    source_tg = CUI.util.copyObject(this.getData(), true);
    migration = this.getMigration();
    find_tags = function(search_tag, tags) {
      var dn_search_tag;
      dn_search_tag = ez5.loca.getBestFrontendValue(search_tag.tag.displayname).trim();
      return tags.filter((function(_this) {
        return function(arg) {
          var tag;
          tag = arg.tag;
          return ez5.loca.getBestFrontendValue(tag.displayname).trim() === dn_search_tag;
        };
      })(this));
    };
    add = true;
    dn_source = ez5.loca.getBestFrontendValue(source_tg.taggroup.displayname).trim();
    if (action_data.mode === "replace") {
      if (!CUI.util.isEmpty(dn_source)) {
        for (idx = i = 0, len = target.length; i < len; idx = ++i) {
          tg = target[idx];
          if (ez5.loca.getBestFrontendValue(tg.taggroup.displayname).trim() !== dn_source) {
            continue;
          }
          if (!tg.taggroup._id) {
            continue;
          }
          if (tg.__update) {
            continue;
          }
          new_taggroup = {
            _basetype: "taggroup",
            __update: true,
            taggroup: {
              _id: tg.taggroup._id,
              type: source_tg.taggroup.type,
              displayname: source_tg.taggroup.displayname
            },
            _tags: []
          };
          newTags = new Set();
          ref = source_tg._tags;
          for (j = 0, len1 = ref.length; j < len1; j++) {
            source_tag = ref[j];
            target_tags = find_tags(source_tag, tg._tags);
            new_tag = source_tag;
            if (target_tags.length <= 1) {
              if (((ref1 = target_tags[0]) != null ? ref1.tag._id : void 0) !== new_tag.tag._id) {
                delete new_tag.tag._id;
              }
              newTags.add(new_tag);
            } else {
              for (k = 0, len2 = target_tags.length; k < len2; k++) {
                tag = target_tags[k];
                newTags.add(tag);
              }
              this.log("Found multiple tags with name '" + (ez5.loca.getBestFrontendValue(target_tags[0].tag.displayname).trim()) + "'. Can't safely distinguish which to update, needs to be fixed manually!");
            }
          }
          new_taggroup._tags = Array.from(newTags);
          add = false;
          target[idx] = new_taggroup;
          console.info("Taggroup:", dn_source, "updated.");
          break;
        }
      }
    }
    if (add) {
      new_taggroup = source_tg;
      delete new_taggroup.taggroup._id;
      delete new_taggroup._tag_identifier;
      ref2 = new_taggroup._tags;
      for (l = 0, len3 = ref2.length; l < len3; l++) {
        tag = ref2[l];
        delete tag.tag._id;
      }
      target.push(new_taggroup);
      console.info("Taggroup:", dn_source, "added.");
    }
    if (indexOf.call(action_data.migrate, "acl") < 0) {
      ref3 = new_taggroup._tags;
      for (m = 0, len4 = ref3.length; m < len4; m++) {
        tag = ref3[m];
        tag._acl = [];
      }
    } else {
      ref4 = new_taggroup._tags;
      for (n = 0, len5 = ref4.length; n < len5; n++) {
        tag = ref4[n];
        new_acl = migration.migrateACL(tag._acl);
        tag._acl = new_acl;
      }
    }
    return this;
  };

  BaseMigrationNodeTagGroup.getSourceNodesFromData = function(migration, data) {
    var i, len, taggroup, taggroups;
    taggroups = [];
    for (i = 0, len = data.length; i < len; i++) {
      taggroup = data[i];
      taggroups.push(new BaseMigrationNodeTagGroup({
        migration: migration,
        data: taggroup
      }));
    }
    return [
      new BaseMigrationNodeTagGroups({
        migration: migration,
        children: taggroups
      })
    ];
  };

  return BaseMigrationNodeTagGroup;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeGroups,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeGroups = (function(superClass) {
  extend(BaseMigrationNodeGroups, superClass);

  function BaseMigrationNodeGroups() {
    return BaseMigrationNodeGroups.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeGroups.prototype.getDisplayText = function() {
    return $$("base.migration.node.groups.text");
  };

  BaseMigrationNodeGroups.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeGroups.prototype.getActionFields = function() {
    var c, fields, i, len, ots, ref;
    ots = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      ots.push(c.getDisplayText());
    }
    fields = BaseMigrationNodeGroup.prototype.getActionFields.call(this);
    fields[0] = {
      type: CUI.Output,
      form: {
        label: $$("base.migration.node.groups.text")
      },
      text: ots.join(", ")
    };
    return fields;
  };

  BaseMigrationNodeGroups.prototype.migrate = function(ev, action_data) {
    var c, i, len, new_groups, ref;
    new_groups = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      new_groups.push.apply(new_groups, c.migrateGroups(action_data));
    }
    if (ev.hasModifierKey()) {
      console.debug("migrate Groups:", CUI.util.dump(new_groups), new_groups);
      return CUI.resolvedPromise();
    }
    return BaseMigrationNodeGroup.prototype.saveGroups.call(this, new_groups);
  };

  BaseMigrationNodeGroups.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  return BaseMigrationNodeGroups;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeGroupType,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeGroupType = (function(superClass) {
  extend(BaseMigrationNodeGroupType, superClass);

  function BaseMigrationNodeGroupType() {
    return BaseMigrationNodeGroupType.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeGroupType.prototype.initOpts = function() {
    BaseMigrationNodeGroupType.__super__.initOpts.call(this);
    return this.addOpts({
      type: {
        mandatory: true,
        check: ["system", "easydb"]
      }
    });
  };

  BaseMigrationNodeGroupType.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeGroupType.prototype.getDisplayText = function() {
    return this._type;
  };

  BaseMigrationNodeGroupType.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodeGroupType.prototype.getActionFields = function() {
    var fields;
    fields = BaseMigrationNodeGroup.prototype.getActionFields.call(this);
    if (this._type === "system") {
      fields.splice(2, 1);
    }
    return fields;
  };

  BaseMigrationNodeGroupType.prototype.migrate = function(ev, action_data) {
    var new_groups;
    new_groups = this.migrateGroups(action_data);
    if (ev.hasModifierKey()) {
      console.debug("migrate Groups:", CUI.util.dump(new_groups), new_groups);
      return CUI.resolvedPromise();
    }
    return BaseMigrationNodeGroup.prototype.saveGroups.call(this, new_groups).done((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.group.type.migrated.md", {
          count: new_groups.length,
          type: _this._type
        }));
      };
    })(this));
  };

  BaseMigrationNodeGroupType.prototype.migrateGroups = function(action_data) {
    var c, i, len, new_group, new_groups, ref;
    new_groups = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      new_group = c.migrateGroup(action_data);
      new_groups.push(new_group);
    }
    return new_groups;
  };

  return BaseMigrationNodeGroupType;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeGroup,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

BaseMigrationNodeGroup = (function(superClass) {
  extend(BaseMigrationNodeGroup, superClass);

  function BaseMigrationNodeGroup() {
    return BaseMigrationNodeGroup.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeGroup.prototype.getDisplayText = function() {
    return ez5.loca.getBestFrontendValue(this.getData().group.displayname);
  };

  BaseMigrationNodeGroup.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeGroup.prototype.getActionFields = function() {
    var fields, ref;
    fields = [
      {
        type: CUI.Output,
        form: {
          label: this.children ? $$("base.migration.node.groups.text") : $$("base.migration.node.group.text")
        },
        text: this.getDisplayText()
      }, {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.common.selection")
        },
        options: [
          {
            text: $$("base.migration.node.group.migrate_acl"),
            value: "acl"
          }, {
            text: $$("base.migration.node.group.migrate_system_rights"),
            value: "system_rights"
          }
        ]
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
    if (((ref = this.getData().group) != null ? ref.type : void 0) === "system") {
      fields.splice(2, 1);
    }
    return fields;
  };

  BaseMigrationNodeGroup.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodeGroup.prototype.migrate = function(ev, action_data) {
    var new_group;
    new_group = this.migrateGroup(action_data);
    if (ev.hasModifierKey()) {
      console.debug("migrate Group:", CUI.util.dump(new_group), new_group);
      return CUI.resolvedPromise();
    }
    return this.saveGroups([new_group]);
  };

  BaseMigrationNodeGroup.prototype.migrateGroup = function(action_data) {
    var _group, compareGroupRef, get_group_name, i, j, k, l, len, len1, len2, migration, new_acl, new_group, ref, ref1, ref2, ref3, source_gn, source_group;
    source_group = CUI.util.copyObject(this.getData(), true);
    migration = this.getMigration();
    get_group_name = (function(_this) {
      return function(group) {
        var name, ref;
        name = (ref = group.group.name) != null ? ref.trim() : void 0;
        if (CUI.util.isEmpty(name)) {
          name = ez5.loca.getBestFrontendValue(group.group.displayname);
        }
        if (CUI.util.isEmpty(name)) {
          return null;
        }
        return name;
      };
    })(this);
    compareGroupRef = function(source_group, target_group) {
      var ref, ref1;
      if (CUI.util.isEmpty(source_group.group.reference) || CUI.util.isEmpty(target_group.group.reference)) {
        return false;
      }
      if (!ez5.version("6")) {
        return false;
      }
      return ((ref = source_group.group.reference) != null ? ref.trim() : void 0) === ((ref1 = target_group.group.reference) != null ? ref1.trim() : void 0);
    };
    source_gn = get_group_name(source_group);
    console.debug("migrate group", source_gn, action_data, source_group);
    new_group = {
      _basetype: "group",
      _acl: void 0,
      _system_rights: void 0,
      group: {
        _id: void 0,
        _version: 1
      }
    };
    if ((source_group.group.type === "system" || action_data.mode === "replace") && !CUI.util.isEmpty(source_gn)) {
      ref = this.getMigration().getBaseData().group;
      for (i = 0, len = ref.length; i < len; i++) {
        _group = ref[i];
        if ((source_gn != null ? source_gn.toLowerCase() : void 0) === ((ref1 = get_group_name(_group)) != null ? ref1.toLowerCase() : void 0) || compareGroupRef(source_group, _group)) {
          console.info("found group:", source_gn, "update...");
          new_group.group._id = _group.group._id;
          new_group.group._version = _group.group._version + 1;
          break;
        }
      }
    }
    ref2 = ["displayname", "frontend_prefs", "name", "type", "authorization_info", "comment", "reference"];
    for (j = 0, len1 = ref2.length; j < len1; j++) {
      k = ref2[j];
      if (!new_group.group[k]) {
        new_group.group[k] = CUI.util.copyObject(source_group.group[k], true);
      }
    }
    if (source_group.group.type === "system") {
      delete new_group.group["reference"];
    }
    if (indexOf.call(action_data.migrate, "system_rights") >= 0) {
      new_group._system_rights = CUI.util.copyObject(source_group._system_rights, true);
    }
    if (indexOf.call(action_data.migrate, "acl") >= 0) {
      new_acl = migration.migrateACL(source_group._acl);
      if (new_acl.length > 0) {
        new_group._acl = new_acl;
      }
    }
    if (ez5.version("6")) {
      ref3 = ["_ip_subnet_filter", "_pseudonymization", "_auth_method_group_maps"];
      for (l = 0, len2 = ref3.length; l < len2; l++) {
        k = ref3[l];
        if (source_group[k]) {
          new_group[k] = CUI.util.copyObject(source_group[k], true);
        }
      }
    }
    return new_group;
  };

  BaseMigrationNodeGroup.prototype.saveGroups = function(groups) {
    var dfr, fail;
    this.log($$("base.migration.console.log.group.saving.md", {
      count: groups.length
    }));
    fail = (function(_this) {
      return function() {
        _this.log($$("base.migration.console.log.group.saving-failed.md", {
          count: groups.length
        }));
        return dfr.reject.apply(dfr.reject, arguments);
      };
    })(this);
    dfr = new CUI.Deferred();
    ez5.api.group({
      type: "POST",
      json_data: groups
    }).done((function(_this) {
      return function(groups) {
        console.debug("groups done...", groups);
        return ez5.api.group({
          type: "GET"
        }).done(function(_groups) {
          _this.log($$("base.migration.console.log.group.migrated.md", {
            count: groups.length
          }));
          console.debug("groups updated...", groups);
          _this.getMigration().getBaseData().group = _groups;
          return dfr.resolve();
        }).fail(dfr.reject);
      };
    })(this)).fail(dfr.reject);
    return dfr.promise();
  };

  BaseMigrationNodeGroup.getSourceNodesFromData = function(migration, data) {
    var group, groups, i, len, type;
    groups = {
      easydb: [],
      system: []
    };
    for (i = 0, len = data.length; i < len; i++) {
      group = data[i];
      type = group.group.type;
      if (type === "easydb" || type === "system") {
        groups[type].push(new BaseMigrationNodeGroup({
          migration: migration,
          data: group
        }));
      }
    }
    return [
      new BaseMigrationNodeGroups({
        migration: migration,
        children: [
          new BaseMigrationNodeGroupType({
            migration: migration,
            type: "system",
            children: groups.system
          }), new BaseMigrationNodeGroupType({
            migration: migration,
            type: "easydb",
            children: groups.easydb
          })
        ]
      })
    ];
  };

  return BaseMigrationNodeGroup;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeTransitions,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeTransitions = (function(superClass) {
  extend(BaseMigrationNodeTransitions, superClass);

  function BaseMigrationNodeTransitions() {
    return BaseMigrationNodeTransitions.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeTransitions.prototype.getDisplayText = function() {
    return "Workflows";
  };

  BaseMigrationNodeTransitions.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodeTransitions.prototype.migrate = function(ev, action_data) {
    var c, copied_transition, i, len, migration, ref, target;
    migration = this.getMigration();
    if (action_data === "replace") {
      target = [];
    } else {
      target = CUI.util.copyObject(migration.getBaseData().transitions, true);
    }
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      c = ref[i];
      copied_transition = migration.migrateTransition(c.getData());
      if (copied_transition) {
        target.push(copied_transition);
      }
    }
    if (ev.hasModifierKey()) {
      console.debug("migrate Transitions:", CUI.util.dump(target), target);
      return CUI.resolvedPromise();
    }
    return BaseMigrationNodeTransition.prototype.saveTransitions.call(this, target);
  };

  BaseMigrationNodeTransitions.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  return BaseMigrationNodeTransitions;

})(BaseMigrationNodeObjecttypes);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeTransition,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeTransition = (function(superClass) {
  extend(BaseMigrationNodeTransition, superClass);

  function BaseMigrationNodeTransition() {
    return BaseMigrationNodeTransition.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeTransition.prototype.getDisplayText = function() {
    return this.getData().operations.join(", ");
  };

  BaseMigrationNodeTransition.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodeTransition.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Output,
        placeholder: $$("base.migration.node.transition.no-settings")
      }
    ];
  };

  BaseMigrationNodeTransition.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodeTransition.prototype.migrate = function(ev, action_data) {
    var copied_transition, migration, target;
    migration = this.getMigration();
    target = CUI.util.copyObject(migration.getBaseData().transitions, true);
    copied_transition = migration.migrateTransition(this.getData());
    if (copied_transition) {
      target.push(copied_transition);
    }
    if (ev.hasModifierKey()) {
      console.debug("migrate Transition:", copied_transition, CUI.util.dump(target), target);
      return CUI.resolvedPromise();
    }
    return CUI.rejectedPromise();
  };

  BaseMigrationNodeTransition.prototype.saveTransitions = function(transitions) {
    this.log($$("base.migration.console.log.transition.saving.md", {
      count: transitions.length
    }));
    return ez5.api.transitions({
      type: "POST",
      json_data: transitions
    }).done((function(_this) {
      return function(transitions) {
        _this.log($$("base.migration.console.log.transition.migrated.md", {
          count: transitions.length
        }));
        console.debug("updating base data:", transitions);
        return _this.getMigration().getBaseData().transitions = transitions;
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.transition.failed"));
      };
    })(this));
  };

  BaseMigrationNodeTransition.getSourceNodesFromData = function(migration, data) {
    var i, len, transition, transitions;
    transitions = [];
    for (i = 0, len = data.length; i < len; i++) {
      transition = data[i];
      transitions.push(new BaseMigrationNodeTransition({
        migration: migration,
        data: transition
      }));
    }
    return [
      new BaseMigrationNodeTransitions({
        migration: migration,
        children: transitions
      })
    ];
  };

  return BaseMigrationNodeTransition;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodeTag,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodeTag = (function(superClass) {
  extend(BaseMigrationNodeTag, superClass);

  function BaseMigrationNodeTag() {
    return BaseMigrationNodeTag.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodeTag.prototype.readOpts = function() {
    return BaseMigrationNodeTag.__super__.readOpts.call(this);
  };

  BaseMigrationNodeTag.prototype.getDisplayText = function() {
    return ez5.loca.getBestFrontendValue(this.getData().tag.displayname);
  };

  BaseMigrationNodeTag.prototype.isSelectable = function() {
    return false;
  };

  return BaseMigrationNodeTag;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodePresets,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodePresets = (function(superClass) {
  extend(BaseMigrationNodePresets, superClass);

  function BaseMigrationNodePresets() {
    return BaseMigrationNodePresets.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodePresets.prototype.getDisplayText = function() {
    return $$("base.migration.node.presets.text");
  };

  BaseMigrationNodePresets.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodePresets.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodePresets.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodePresets.prototype.migrate = function(ev, actionData) {
    var child, i, len, migratePromises, ref;
    migratePromises = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      child = ref[i];
      migratePromises.push(child.migrate(ev, actionData));
    }
    return CUI.when(migratePromises);
  };

  return BaseMigrationNodePresets;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodePreset,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodePreset = (function(superClass) {
  extend(BaseMigrationNodePreset, superClass);

  function BaseMigrationNodePreset() {
    return BaseMigrationNodePreset.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodePreset.prototype.initOpts = function() {
    BaseMigrationNodePreset.__super__.initOpts.call(this);
    return this.addOpts({
      context: {
        mandatory: true
      }
    });
  };

  BaseMigrationNodePreset.prototype.getDisplayText = function() {
    return ez5.loca.getBestFrontendValue(this.getData().right_preset.displayname);
  };

  BaseMigrationNodePreset.getSourceNodesFromData = function(migration, data) {
    var children, context, contextChildren, contextData, i, len, preset;
    children = [];
    for (context in data) {
      contextData = data[context];
      contextChildren = [];
      for (i = 0, len = contextData.length; i < len; i++) {
        preset = contextData[i];
        contextChildren.push(new BaseMigrationNodePreset({
          migration: migration,
          data: preset,
          context: context
        }));
      }
      children.push(new BaseMigrationNodePresetContext({
        migration: migration,
        context: context,
        children: contextChildren
      }));
    }
    return [
      new BaseMigrationNodePresets({
        migration: migration,
        children: children
      })
    ];
  };

  BaseMigrationNodePreset.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodePreset.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodePreset.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Output,
        form: {
          label: this.children ? $$("base.migration.node.presets.text") : $$("base.migration.node.preset.text")
        },
        text: this.getDisplayText()
      }
    ];
  };

  BaseMigrationNodePreset.prototype.migrate = function() {
    var position, presetData;
    position = BaseMigrationNodePresetContext.prototype.getNextPresetPosition.apply(this);
    presetData = this.getPreset(position);
    return BaseMigrationNodePresetContext.prototype.savePresets.apply(this, [[presetData]]);
  };

  BaseMigrationNodePreset.prototype.getPreset = function(position) {
    var data;
    data = this.getData();
    data.right_preset._position = position;
    data.right_preset._version = 1;
    delete data.right_preset._id;
    return data;
  };

  return BaseMigrationNodePreset;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodePresetContext,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty;

BaseMigrationNodePresetContext = (function(superClass) {
  extend(BaseMigrationNodePresetContext, superClass);

  function BaseMigrationNodePresetContext() {
    return BaseMigrationNodePresetContext.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodePresetContext.prototype.initOpts = function() {
    BaseMigrationNodePresetContext.__super__.initOpts.call(this);
    return this.addOpts({
      context: {
        mandatory: true
      }
    });
  };

  BaseMigrationNodePresetContext.prototype.getDisplayText = function() {
    return $$("acl.rights.context." + this._context);
  };

  BaseMigrationNodePresetContext.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    return pane;
  };

  BaseMigrationNodePresetContext.prototype.checkMigrateButton = function() {
    return this.__migrateBtn.enable();
  };

  BaseMigrationNodePresetContext.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Output,
        form: {
          label: $$("base.migration.node.presets.text")
        },
        text: this.getDisplayText()
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodePresetContext.prototype.migrate = function(ev, actionData) {
    var child, deferred, i, len, position, presets, ref;
    position = actionData.mode === "add" ? this.getNextPresetPosition() : 0;
    presets = [];
    ref = this.children;
    for (i = 0, len = ref.length; i < len; i++) {
      child = ref[i];
      presets.push(child.getPreset(position));
      position++;
    }
    if (actionData.mode === "add") {
      return this.savePresets(presets);
    } else {
      deferred = new CUI.Deferred();
      this.deleteCurrentPresets().done((function(_this) {
        return function() {
          return _this.savePresets(presets).done(deferred.resolve).fail(deferred.reject);
        };
      })(this)).fail(deferred.reject);
      return deferred.promise();
    }
  };

  BaseMigrationNodePresetContext.prototype.getNextPresetPosition = function() {
    var presets, ref;
    presets = this.getMigration().getBaseData().preset[this._context] || [];
    return (((ref = presets[presets.length - 1]) != null ? ref.right_preset._position : void 0) + 1) || 0;
  };

  BaseMigrationNodePresetContext.prototype.savePresets = function(presets) {
    this.log($$("base.migration.console.log.presets.saving.md", {
      count: presets.length,
      context: this.getDisplayText()
    }));
    return ez5.api.right({
      type: "POST",
      api: "/" + this._context + "/presets",
      json_data: presets
    }).done((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.presets.migrated.md", {
          count: presets.length,
          context: _this.getDisplayText()
        }));
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.presets.saving-failed.md", {
          count: presets.length,
          context: _this.getDisplayText()
        }));
      };
    })(this));
  };

  BaseMigrationNodePresetContext.prototype.deleteCurrentPresets = function() {
    var deletePromises, i, len, preset, presets;
    deletePromises = [];
    presets = this.getMigration().getBaseData().preset[this._context] || [];
    this.log($$("base.migration.console.log.presets.removing.md", {
      count: presets.length,
      context: this.getDisplayText()
    }));
    for (i = 0, len = presets.length; i < len; i++) {
      preset = presets[i];
      deletePromises.push(this.__deletePreset(preset));
    }
    return CUI.when(deletePromises).done((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.presets.removed.md", {
          count: presets.length,
          context: _this.getDisplayText()
        }));
      };
    })(this)).fail((function(_this) {
      return function() {
        return _this.log($$("base.migration.console.log.presets.removing-failed.md", {
          count: presets.length,
          context: _this.getDisplayText()
        }));
      };
    })(this));
  };

  BaseMigrationNodePresetContext.prototype.__deletePreset = function(preset) {
    var id;
    id = preset.right_preset._id;
    return ez5.api.right({
      type: "DELETE",
      api: "/" + this._context + "/presets/" + id
    });
  };

  return BaseMigrationNodePresetContext;

})(BaseMigrationNodeData);
// Generated by CoffeeScript 1.12.7
var BaseMigrationNodePool,
  extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  hasProp = {}.hasOwnProperty,
  indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

BaseMigrationNodePool = (function(superClass) {
  extend(BaseMigrationNodePool, superClass);

  function BaseMigrationNodePool() {
    return BaseMigrationNodePool.__super__.constructor.apply(this, arguments);
  }

  BaseMigrationNodePool.prototype.getDisplayText = function() {
    return ez5.loca.getBestFrontendValue(this.getData().pool.name);
  };

  BaseMigrationNodePool.prototype.hasRightPane = function() {
    return true;
  };

  BaseMigrationNodePool.prototype.getActionPane = function() {
    var pane;
    pane = this.getActionPaneBase();
    ez5.api.pool().done((function(_this) {
      return function(pools) {
        var target_pools;
        target_pools = BaseMigrationNodePool.buildPoolTree(_this.getMigration(), pools);
        target_pools.sort(function(poolNode, nextPoolNode) {
          return poolNode.getDisplayText().localeCompare(nextPoolNode.getDisplayText());
        });
        _this.__targetTree = new CUI.ListViewTree({
          cols: ["maximize"],
          selectableRows: true,
          header_left: new CUI.Label({
            text: $$("base.migration.node.pool.target.text")
          }),
          children: target_pools,
          onSelect: function() {
            return _this.checkMigrateButton();
          },
          onDeselect: function() {
            return _this.checkMigrateButton();
          }
        });
        _this.getLayout().replace(_this.__targetTree.render(), "right");
        return _this.__targetTree.root.open();
      };
    })(this));
    return pane;
  };

  BaseMigrationNodePool.prototype.getActionFields = function() {
    return [
      {
        type: CUI.Output,
        form: {
          label: $$("base.migration.node.pool.text")
        },
        text: this.getDisplayText()
      }, {
        type: CUI.Options,
        name: "migrate",
        form: {
          label: $$("base.migration.common.selection")
        },
        options: [
          {
            text: $$("base.migration.node.pool.check_acl", {
              acl_count: this.getData()._acl.length
            }),
            disabled: this.getData()._acl.length === 0,
            value: "acl"
          }
        ]
      }, {
        type: CUI.Options,
        name: "mode",
        radio: true,
        form: {
          label: $$("base.migration.common.options")
        },
        options: [
          {
            text: $$("base.migration.common.replace"),
            value: "replace"
          }, {
            text: $$("base.migration.common.add"),
            value: "add"
          }
        ]
      }
    ];
  };

  BaseMigrationNodePool.prototype.migrate = function(ev, action_data) {
    var do_save, migration, new_acl, save_pool, source_pool, target_pool, target_pool_node;
    console.debug("migrate Pool:", this.getDisplayText());
    target_pool_node = this.__targetTree.getSelectedNode();
    target_pool = target_pool_node.getData();
    source_pool = this.getData();
    migration = this.getMigration();
    save_pool = {
      _basetype: "pool",
      pool: {
        _id: target_pool.pool._id,
        _id_parent: target_pool.pool._id_parent,
        _version: target_pool.pool._version + 1
      }
    };
    if (target_pool.pool.is_system_pool) {
      delete save_pool.pool._id_parent;
    }
    do_save = false;
    if (indexOf.call(action_data.migrate, "acl") >= 0) {
      new_acl = migration.migrateACL(source_pool._acl);
      if (new_acl.length > 0) {
        save_pool._acl = [];
        if (action_data.mode === "add") {
          save_pool._acl.push.apply(save_pool._acl, target_pool._acl);
        }
        save_pool._acl.push.apply(save_pool._acl, new_acl);
        save_pool._private_acl = source_pool._private_acl;
        do_save = true;
      }
    }
    if (!do_save) {
      console.debug("no migratable data.");
      return CUI.resolvedPromise();
    }
    if (ev.hasModifierKey()) {
      console.debug("pool save:", CUI.util.dump(save_pool));
      return CUI.resolvedPromise();
    }
    this.log($$("base.migration.console.log.pool.saving.md", {
      name: this.getDisplayText()
    }));
    return ez5.api.pool({
      type: "POST",
      json_data: [save_pool]
    }).done((function(_this) {
      return function(pool_data) {
        _this.log($$("base.migration.console.log.pool.saved.md", {
          name: _this.getDisplayText(),
          count_acl: save_pool._acl.length
        }));
        console.debug("pool_data", pool_data);
        return target_pool_node.setData(pool_data[0]);
      };
    })(this));
  };

  BaseMigrationNodePool.prototype.checkMigrateButton = function() {
    var ref;
    this.__migrateBtn.disable();
    if (!((ref = this.__targetTree) != null ? ref.getSelectedNode() : void 0)) {
      return;
    }
    if (this.__actionData.migrate.length === 0) {
      return;
    }
    this.__migrateBtn.enable();
  };

  BaseMigrationNodePool.buildPoolTree = function(migration, data) {
    console.debug("building pool tree", data);
    return ez5.buildObjectTree({
      objects: data,
      objectKey: "pool",
      doOpen: false,
      newInstanceFunc: function(o) {
        return new BaseMigrationNodePool({
          migration: migration,
          data: o
        });
      }
    });
  };

  BaseMigrationNodePool.getSourceNodesFromData = function(migration, data) {
    var pools;
    pools = BaseMigrationNodePool.buildPoolTree(migration, data);
    pools.sort((function(_this) {
      return function(a, b) {
        return a.getDisplayText().localeCompare(b.getDisplayText());
      };
    })(this));
    return [
      new BaseMigrationNodeStructure({
        migration: migration,
        name: $$("base.migration.node.pool.pools.text"),
        children: pools
      })
    ];
  };

  return BaseMigrationNodePool;

})(BaseMigrationNodeData);
