// Generated by CoffeeScript 1.12.7
var 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;

Easydb4Migration.Rgzm = (function(superClass) {
  extend(Rgzm, superClass);

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

  Rgzm.prototype.name = function() {
    return "rgzm";
  };

  Rgzm.prototype.init = function() {
    var dfr;
    this.sys_by_ref = {
      systematik: {}
    };
    this.__itemtyp = {};
    this.editmask_by_ref = {};
    this.first_item_idx = void 0;
    dfr = new CUI.Deferred();
    this._migration.query('SELECT * FROM "source.rgzm.itemtyp"').fail(dfr.reject).done((function(_this) {
      return function(result) {
        var i, len, ref1, row;
        ref1 = result.rows;
        for (i = 0, len = ref1.length; i < len; i++) {
          row = ref1[i];
          _this.__itemtyp["itemtyp:" + row[0]] = row;
        }
        _this._migration.query("SELECT 'item:'||a.id AS reference, b.editmask\n  FROM \"source.rgzm.item\" a\n  LEFT JOIN \"source.rgzm.itemtyp\" b ON (a.lk_itemtyp = b.id)").fail(dfr.reject).done(function(result) {
          var j, len1, ref2;
          ref2 = result.rows;
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            row = ref2[j];
            _this.editmask_by_ref[row.reference] = row.editmask;
          }
          console.debug("editmask_by_ref", _this.editmask_by_ref);
          dfr.resolve();
        });
      };
    })(this));
    return dfr.promise();
  };

  Rgzm.prototype.copy_sys = function(new_target, ref) {
    var source_sys;
    source_sys = this.sys_by_ref.systematik[ref];
    if (!source_sys) {
      this._migration.logerror("Could not find systematik with reference: " + ref + ". Skipping.");
      return;
    }
    if (!this.sys_by_ref[new_target]) {
      this.sys_by_ref[new_target] = {};
    }
    if (this.sys_by_ref[new_target][ref]) {
      return;
    }
    this.sys_by_ref[new_target][ref] = source_sys;
    if (source_sys.systematik["lookup:_id_parent"]) {
      this.copy_sys(new_target, source_sys.systematik["lookup:_id_parent"].easydb4_reference);
    }
  };

  Rgzm.prototype.map_typ_sys = {
    1: "raeumlich",
    2: "raeumlich",
    3: "raeumlich",
    7: "raeumlich",
    9: "raeumlich",
    17: "raeumlich",
    18: "raeumlich",
    32: "material_standard",
    33: "objekttyp",
    34: "technik",
    6: "zeitlich_einordnung",
    10: "zeitlich_einordnung",
    4: "verwahrorte",
    5: "rgzm_intern",
    13: "rgzm_intern",
    15: "rgzm_intern",
    16: "rgzm_intern",
    19: "rgzm_intern",
    20: "rgzm_intern",
    21: "rgzm_intern",
    23: "rgzm_intern",
    24: "rgzm_intern",
    28: "rgzm_intern",
    29: "rgzm_intern",
    21: "rgzm_intern",
    31: "rgzm_intern",
    35: "rgzm_intern",
    36: "rgzm_intern",
    37: "rgzm_intern",
    38: "rgzm_intern",
    8: "publikationen",
    11: "publikationen"
  };

  Rgzm.prototype.map_nested_filter = {
    "_nested:item__item_objekt_1364": "ItemEdit_Objekt",
    "_nested:item__item_werkblatt_1409": "ItemEdit_Werkblatt",
    "_nested:item__item_foto_1510": "ItemEdit_Foto"
  };

  Rgzm.prototype.payload = function(filename, json, update, store_file, filename_idx) {
    var find_sys, fn, i, idx, init_json, item, itemtyp, j, k, l, len, len1, len2, len3, m, nes_key, nested_map_keys, new_entry, new_json, new_ot, new_sys, nummer, obj, objects, payload_idx, pool_ref, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, sys_entries, sys_entry, sys_link, typ, v, warn;
    if (json.objecttype === "systematik") {
      ref1 = json.objects;
      for (i = 0, len = ref1.length; i < len; i++) {
        obj = ref1[i];
        this.sys_by_ref.systematik[obj.systematik.easydb4_reference] = obj;
      }
    }
    if (json.objecttype === "item") {
      if (this.first_item_idx === void 0) {
        this.first_item_idx = filename_idx;
      }
      find_sys = (function(_this) {
        return function(item) {
          var item2, j, k, len1, v;
          for (k in item) {
            v = item[k];
            if (CUI.util.isArray(v)) {
              for (j = 0, len1 = v.length; j < len1; j++) {
                item2 = v[j];
                find_sys(item2);
              }
              continue;
            }
            if (item[k + ":source_name"] === "systematik") {
              _this.copy_sys(v._objecttype, v[v._objecttype]["lookup:_id"].easydb4_reference);
            }
          }
        };
      })(this);
      nested_map_keys = Object.keys(this.map_nested_filter);
      ref2 = json.objects;
      for (j = 0, len1 = ref2.length; j < len1; j++) {
        obj = ref2[j];
        pool_ref = obj.item._pool.pool["lookup:_id"].reference;
        itemtyp = this.__itemtyp[pool_ref];
        nummer = obj.item.nummer;
        if (nummer) {
          delete obj.item.nummer;
          if (itemtyp.praefix) {
            nummer = itemtyp.praefix + nummer;
          }
          obj.item.nummer = nummer;
        }
        ref3 = obj.item;
        for (k in ref3) {
          v = ref3[k];
          if (!k.startsWith("_nested:item__item_item")) {
            continue;
          }
          CUI.util.removeFromArray(null, v, (function(_this) {
            return function(v) {
              var ref4, ref5, ref6;
              if (!obj.item.easydb4_reference) {
                return false;
              }
              if (((ref4 = v.lk_item_to) != null ? (ref5 = ref4.item) != null ? (ref6 = ref5["lookup:_id"]) != null ? ref6.easydb4_reference : void 0 : void 0 : void 0) === obj.item.easydb4_reference) {
                _this._migration.logwarn("Removing self-referencing " + k + ": " + obj.item.easydb4_reference);
                return true;
              }
              return false;
            };
          })(this));
        }
        find_sys(obj.item);
        ref4 = obj.item;
        for (k in ref4) {
          v = ref4[k];
          if (k === "_version" && v === 2) {
            delete obj.item[k];
            obj.item["_version:auto_increment"] = true;
          }
          if (k.startsWith("_nested:")) {
            if (k === "_nested:item__item_item") {
              obj.item[k + ":group_mode"] = "append";
            } else {
              obj.item[k + ":group_mode"] = "replace";
            }
          }
          if (k === "express_lk_to_id") {
            obj.item["_nested:item__express_lk_to_id_neu"] = [
              {
                express_lk_to_id: v
              }
            ];
          }
          if (k === "_nested:item__datatree_old") {
            for (l = 0, len2 = v.length; l < len2; l++) {
              item = v[l];
              if (!item.cat_id) {
                continue;
              }
              sys_link = CUI.util.copyObject(item.cat_id, true);
              ref = (ref5 = sys_link.systematik) != null ? (ref6 = ref5["lookup:_id"]) != null ? ref6.easydb4_reference : void 0 : void 0;
              if (!ref) {
                continue;
              }
              sys_entry = this.sys_by_ref.systematik[ref];
              typ = sys_entry.systematik.lk_typ.typ["lookup:_id"].easydb4_reference.substr(4);
              new_sys = this.map_typ_sys[typ];
              if (!new_sys) {
                warn = "Unknown systematik typ: " + typ + ". Skipping.";
                this._migration.logwarn(warn);
                continue;
              }
              this.copy_sys("systematik_" + new_sys, ref);
              sys_link._objecttype = "systematik_" + new_sys;
              sys_link[sys_link._objecttype] = sys_link.systematik;
              delete sys_link.systematik;
              nes_key = "_nested:item__" + sys_link._objecttype;
              if (!obj.item[nes_key]) {
                obj.item[nes_key] = [];
                obj.item[nes_key + ":group_mode"] = "replace";
              }
              obj.item[nes_key].push({
                lk_systematik_id: sys_link
              });
            }
          }
        }
      }
    }
    if (filename === "basetype_user_ldap_sso.json") {
      payload_idx = this.first_item_idx;
      ref7 = this.sys_by_ref;
      for (new_ot in ref7) {
        sys_entries = ref7[new_ot];
        if (new_ot === "systematik") {
          continue;
        }
        objects = [];
        for (ref in sys_entries) {
          sys_entry = sys_entries[ref];
          new_entry = CUI.util.copyObject(sys_entry, true);
          new_entry[new_ot] = new_entry[new_entry._objecttype];
          delete new_entry[new_entry._objecttype];
          new_entry._objecttype = new_ot;
          objects.push(new_entry);
        }
        objects.sort(function(a, b) {
          if (a._depth < b._depth) {
            return -1;
          } else if (a._depth > b._depth) {
            return 1;
          } else {
            return 0;
          }
        });
        new_json = null;
        init_json = (function(_this) {
          return function() {
            return new_json = {
              import_type: "db",
              objecttype: new_ot,
              objects: []
            };
          };
        })(this);
        init_json();
        for (idx = m = 0, len3 = objects.length; m < len3; idx = ++m) {
          obj = objects[idx];
          new_json.objects.push(obj);
          if (idx === objects.length - 1 || objects[idx + 1]._depth > obj._depth) {
            fn = new_ot + "-" + obj._depth + ".json";
            store_file(fn, new_json, payload_idx);
            payload_idx++;
            init_json();
          }
        }
      }
    }
  };

  return Rgzm;

})(Easydb4MigrationPlugin);

ez5.session_ready((function(_this) {
  return function() {
    return Easydb4Migration.plugins.registerPlugin(Easydb4Migration.Rgzm);
  };
})(this));
