// 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,
  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; };

Easydb4MigrationPlugin.OrdinariatFreiburg = (function(superClass) {
  extend(OrdinariatFreiburg, superClass);

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

  OrdinariatFreiburg.prototype.name = function() {
    return "ordinariat-freiburg";
  };

  OrdinariatFreiburg.prototype.init = function() {
    var dfr, dfr2, dfr3;
    this.gnd_source_field = "lk_gnd_normdaten_id";
    this.gnd_target_field = "gnd_id";
    this.gnd_field_ots = ["arbeitsfeld1", "arbeitsfeld2", "archivalie", "ikonogrbez", "lokalisierung", "objektname", "person", "provenienz", "sachbezeichnung", "schlagwort", "titel", "topographie"];
    console.debug(this.name(), "| init | source field for gnd links:", this.gnd_source_field);
    console.debug(this.name(), "| init | target field for gnd links:", this.gnd_target_field);
    console.debug(this.name(), "| init | objecttypes with gnd link:", this.gnd_field_ots);
    this.item_ot = "item";
    this.item_foto_ot = "item_foto";
    this.objekt_foto_ot = "objekt__foto";
    this.item_item_typ_ot = "item_item_typ";
    this.item_item_typ_created = false;
    this.item_item_typ__ist_kind_von = 'ist Kind von';
    this.item_item_typ__hat_kind = 'hat Kind';
    this.gnd_rows = {};
    dfr = new CUI.Deferred();
    this._migration.query("SELECT\n	id,\n	gnd_uri,\n	gnd_preferred_name,\n	gnd_id || ' ' || replace(gnd_old_authority_number, X'0A', ' ') || ' ' || replace(gnd_fulltext, X'0A', ' ') AS fulltext\nFROM \"source.public.gnd\"\nWHERE id IS NOT NULL\nAND gnd_uri IS NOT NULL").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.gnd_rows[row.id] = row;
        }
        console.debug(_this.name(), "| init | loaded", Object.keys(_this.gnd_rows).length, "rows from source.public.gnd");
        return dfr.resolve();
      };
    })(this));
    this.freigabe_tags = {};
    dfr2 = new CUI.Deferred();
    this._migration.query("SELECT id, name\nFROM \"source.public.freigabe\"\nWHERE id IS NOT NULL\nAND name IS NOT NULL").fail(dfr2.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.freigabe_tags["freigabe:" + row.id] = row.name;
        }
        console.debug(_this.name(), "| init | loaded", Object.keys(_this.freigabe_tags).length, "tags from source.public.freigabe");
        return dfr2.resolve();
      };
    })(this));
    dfr3 = new CUI.Deferred();
    this.itemtyp_objekt_ref = "";
    this.itemtyp_foto_ref = "";
    this._migration.query("SELECT * FROM (\n	SELECT\n		id,\n		'foto' AS internal_name,\n		name\n	FROM \"source.public.itemtyp\"\n	WHERE lower(name) LIKE 'foto%'\n	LIMIT 1 -- there should only be one hit\n)\n\nUNION ALL\n\nSELECT * FROM (\n	SELECT\n		id,\n		'objekt' AS internal_name,\n		name\n	FROM \"source.public.itemtyp\"\n	WHERE lower(name) LIKE 'objekt%'\n	LIMIT 1 -- there should only be one hit\n)").fail(dfr3.reject).done((function(_this) {
      return function(result) {
        var i, itemtyp_foto_id, itemtyp_objekt_id, len, ref1, row;
        itemtyp_foto_id = 0;
        itemtyp_objekt_id = 0;
        ref1 = result.rows;
        for (i = 0, len = ref1.length; i < len; i++) {
          row = ref1[i];
          if (row.internal_name === "objekt") {
            itemtyp_objekt_id = row.id;
            _this.itemtyp_objekt_ref = "itemtyp:" + itemtyp_objekt_id;
            console.debug(_this.name(), "| init | loaded id for itemtyp with name", row.name, "=> ref =", _this.itemtyp_objekt_ref);
          }
          if (row.internal_name === "foto") {
            itemtyp_foto_id = row.id;
            _this.itemtyp_foto_ref = "itemtyp:" + itemtyp_foto_id;
            console.debug(_this.name(), "| init | loaded id for itemtyp with name", row.name, "=> ref =", _this.itemtyp_foto_ref);
          }
        }
        _this.item_references = {};
        _this.dummy_items = {};
        _this.dummys_exported = false;
        _this.item_links = {};
        _this.item_foto_links = {};
        _this.seen_objekt_foto_refs = {};
        _this.hauptfotos = {};
        return _this._migration.query("SELECT\n	item_from.id,\n	item.id AS item_id,\n	'item' AS ot,\n	item.pool_id AS pool_id,\n	NULL AS item_from_id,\n	NULL AS hauptfoto\nFROM \"source.public.item\" item\nJOIN \"source.public.item__item\" item_from\nON (\n	-- item objects that link to this object\n	-- relates to _nested:item__item_1333\n	item.id = item_from.lk_item_from AND\n	item.lk_itemtyp_id = " + itemtyp_objekt_id + ")\n\nUNION ALL\n\nSELECT\n	item_to.id,\n	item.id AS item_id,\n	'item_foto' AS ot,\n	item.pool_id AS pool_id,\n	item_to.lk_item_from AS item_from_id,\n	item_to.hauptfoto\nFROM \"source.public.item\" item\nJOIN \"source.public.item__item\" item_to\nON (\n	-- item_foto objects that are linked to this object using objekt__foto link objects\n	-- relates to _nested:item__item_1272\n	item.id = item_to.lk_item_to AND\n	item.lk_itemtyp_id = " + itemtyp_foto_id + ")").fail(dfr3.reject).done(function(result) {
          var j, len1, ref2;
          ref2 = result.rows;
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            row = ref2[j];
            if (!row.id) {
              continue;
            }
            if (!row.item_id) {
              continue;
            }
            if (!row.ot) {
              continue;
            }
            if (!row.pool_id) {
              continue;
            }
            if (_this.dummy_items[row.ot] == null) {
              _this.dummy_items[row.ot] = {};
            }
            _this.dummy_items[row.ot][_this.item_ot + ":" + row.item_id] = "pool:" + row.pool_id;
            if (row.ot === _this.item_foto_ot) {
              _this.item_foto_links[row.id] = _this.item_ot + ":" + row.item_id;
              if (row.hauptfoto === 1) {
                _this.hauptfotos[_this.item_ot + ":" + row.item_id] = true;
              }
            } else {
              _this.item_links[row.id] = _this.item_ot + ":" + row.item_id;
            }
          }
          if (_this.dummy_items[_this.item_ot] != null) {
            console.debug(_this.name(), "| init | loaded", Object.keys(_this.dummy_items[_this.item_ot]).length, "dummy", _this.item_ot, "objects");
          }
          if (_this.dummy_items[_this.item_foto_ot] != null) {
            console.debug(_this.name(), "| init | loaded", Object.keys(_this.dummy_items[_this.item_foto_ot]).length, "dummy", _this.item_foto_ot, "objects");
          }
          console.debug(_this.name(), "| init | loaded", Object.keys(_this.item_links).length, "item_links");
          console.debug(_this.name(), "| init | loaded", Object.keys(_this.item_foto_links).length, "item_foto_links");
          return dfr3.resolve();
        });
      };
    })(this));
    dfr.promise();
    dfr2.promise();
    return dfr3.promise();
  };

  OrdinariatFreiburg.prototype.format_gnd_link = function(gnd_row) {
    var gnd;
    gnd = {
      conceptURI: gnd_row.gnd_uri,
      frontendLanguage: "de"
    };
    if (gnd_row.gnd_preferred_name) {
      gnd.conceptName = gnd_row.gnd_preferred_name;
      gnd._standard = {
        text: gnd_row.gnd_preferred_name
      };
    }
    if (gnd_row.fulltext) {
      gnd._fulltext = {
        text: gnd_row.fulltext
      };
    } else if (gnd_row.gnd_preferred_name) {
      gnd._fulltext = {
        text: gnd_row.gnd_preferred_name
      };
    }
    return gnd;
  };

  OrdinariatFreiburg.prototype.payload_item = function(filename, json, store_file, filename_idx) {
    var bidi_link_obj, fn, foto_link, hauptfoto, i, init_json, is_hauptfoto, item_fotos, item_item_bidi, item_ref, items, j, k, l, len, len1, len2, len3, len4, len5, len6, m, n, nested_debug, nested_prefix, nested_suffix, new_json, new_nested_key, new_obj, o, obj, obj_ref, objekt_foto_json, objekt_foto_obj, objekt_foto_objects, objekt_link, ot, p, ref1, ref10, ref11, ref2, ref3, ref4, ref5, ref6, ref7, ref8, ref9, rel, seen_item_refs, v;
    ot = json.objecttype;
    console.debug(this.name(), "| objecttype:", ot, "| payload_item()", filename);
    nested_prefix = "_nested:" + ot + "__";
    items = [];
    item_fotos = [];
    objekt_foto_objects = [];
    ref1 = json.objects;
    for (i = 0, len = ref1.length; i < len; i++) {
      obj = ref1[i];
      if (!obj[ot]) {
        continue;
      }
      if (!obj[ot]["easydb4_reference"]) {
        continue;
      }
      obj_ref = obj[ot]["easydb4_reference"];
      if (obj[ot]["lk_itemtyp_id"] != null) {
        if (obj[ot]["lk_itemtyp_id"]["itemtyp"] != null) {
          if (obj[ot]["lk_itemtyp_id"]["itemtyp"]["lookup:_id"] != null) {
            if (obj[ot]["lk_itemtyp_id"]["itemtyp"]["lookup:_id"]["easydb4_reference"] != null) {
              if (obj[ot]["lk_itemtyp_id"]["itemtyp"]["lookup:_id"]["easydb4_reference"] === this.itemtyp_foto_ref) {
                ref2 = ["item_1314", "item_1333", "item_1272"];
                for (j = 0, len1 = ref2.length; j < len1; j++) {
                  nested_suffix = ref2[j];
                  if (obj[ot] == null) {
                    continue;
                  }
                  if (obj[ot][nested_prefix + nested_suffix] == null) {
                    continue;
                  }
                  obj[ot]["__debug:" + nested_prefix + nested_suffix] = [
                    {
                      "skip": "links handled in item objects"
                    }
                  ];
                }
                if (this.dummy_items[this.item_foto_ot] != null) {
                  if (this.dummy_items[this.item_foto_ot][obj_ref] != null) {
                    obj[ot]["lookup:_id"] = {
                      "easydb4_reference": obj_ref
                    };
                    obj[ot]["_version:auto_increment"] = true;
                    delete obj[ot]["_version"];
                  }
                }
                item_fotos.push(obj);
                this.item_references[obj_ref] = this.item_foto_ot;
                continue;
              }
            }
          }
        }
      }
      item_item_bidi = [];
      seen_item_refs = [];
      ref3 = ["item_1314", "item_1333"];
      for (l = 0, len2 = ref3.length; l < len2; l++) {
        nested_suffix = ref3[l];
        if (!obj[ot][nested_prefix + nested_suffix]) {
          continue;
        }
        nested_debug = [];
        ref4 = obj[ot][nested_prefix + nested_suffix];
        for (m = 0, len3 = ref4.length; m < len3; m++) {
          rel = ref4[m];
          if (ref5 = !"__key", indexOf.call(rel, ref5) >= 0) {
            nested_debug.push({
              "skip": "no __key",
              "row": rel
            });
            continue;
          }
          if (ref6 = !"easydb4_reference", indexOf.call(rel, ref6) >= 0) {
            nested_debug.push({
              "skip": "no easydb4_reference",
              "row": rel
            });
            continue;
          }
          hauptfoto = false;
          if (indexOf.call(rel, "hauptfoto") >= 0) {
            hauptfoto = rel["hauptfoto"] === true;
          }
          if (this.item_links[rel["__key"]]) {
            item_ref = this.item_links[rel["__key"]];
            if (obj_ref === item_ref) {
              nested_debug.push({
                "skip": "self link",
                "ref": item_ref,
                "row": rel
              });
              continue;
            }
            if (indexOf.call(seen_item_refs, item_ref) >= 0) {
              nested_debug.push({
                "skip": "duplicate",
                "ref": item_ref,
                "row": rel
              });
              continue;
            }
            seen_item_refs.push(item_ref);
            bidi_link_obj = {
              "easydb4_reference": rel["easydb4_reference"],
              "hauptfoto": hauptfoto,
              "objekt": {
                "_objecttype": this.item_ot,
                "_mask": "_all_fields",
                "item": {
                  "lookup:_id": {
                    "easydb4_reference": item_ref
                  }
                }
              }
            };
            if (nested_suffix === "item_1333") {
              bidi_link_obj["typ"] = this.link_item_item_typ(this.item_item_typ__ist_kind_von);
            }
            item_item_bidi.push(bidi_link_obj);
            nested_debug.push({
              "link_created_in": nested_prefix + "item_item_bidi",
              "ref": item_ref,
              "row": rel
            });
          }
        }
        if (nested_debug.length < 1) {
          nested_debug.push({
            "empty": true
          });
        }
      }
      if (item_item_bidi.length > 0) {
        obj[ot][nested_prefix + "item_item_bidi"] = item_item_bidi;
      }
      seen_item_refs = [];
      nested_suffix = "item_1314";
      if (obj[ot][nested_prefix + nested_suffix] != null) {
        nested_debug = [];
        ref7 = obj[ot][nested_prefix + nested_suffix];
        for (n = 0, len4 = ref7.length; n < len4; n++) {
          rel = ref7[n];
          if (ref8 = !"__key", indexOf.call(rel, ref8) >= 0) {
            nested_debug.push({
              "skip": "no __key",
              "row": rel
            });
            continue;
          }
          if (ref9 = !"easydb4_reference", indexOf.call(rel, ref9) >= 0) {
            nested_debug.push({
              "skip": "no easydb4_reference",
              "row": rel
            });
            continue;
          }
          if (this.item_foto_links[rel["__key"]]) {
            item_ref = this.item_foto_links[rel["__key"]];
            if (obj_ref === item_ref) {
              nested_debug.push({
                "skip": "self link",
                "ref": item_ref,
                "row": rel
              });
              continue;
            }
            if (indexOf.call(seen_item_refs, item_ref) >= 0) {
              nested_debug.push({
                "skip": "duplicate",
                "ref": item_ref,
                "row": rel
              });
              continue;
            }
            seen_item_refs.push(item_ref);
            if (this.seen_objekt_foto_refs[obj_ref] == null) {
              this.seen_objekt_foto_refs[obj_ref] = [];
            }
            if (indexOf.call(this.seen_objekt_foto_refs[obj_ref], item_ref) >= 0) {
              continue;
            }
            objekt_foto_obj = {
              "_objecttype": this.objekt_foto_ot,
              "_mask": "_all_fields"
            };
            objekt_link = {
              "_objecttype": this.item_ot,
              "_mask": "_all_fields"
            };
            objekt_link[this.item_ot] = {
              "lookup:_id": {
                "easydb4_reference": obj_ref
              }
            };
            foto_link = {
              "_objecttype": this.item_foto_ot,
              "_mask": "_all_fields"
            };
            foto_link[this.item_foto_ot] = {
              "lookup:_id": {
                "easydb4_reference": item_ref
              }
            };
            is_hauptfoto = this.hauptfotos[item_ref] != null;
            objekt_foto_obj[this.objekt_foto_ot] = {
              "_version": 1,
              "objekt": objekt_link,
              "foto": foto_link,
              "__is_hauptfoto": is_hauptfoto
            };
            if (is_hauptfoto) {
              objekt_foto_objects.unshift(objekt_foto_obj);
            } else {
              objekt_foto_objects.push(objekt_foto_obj);
            }
            this.seen_objekt_foto_refs[obj_ref].push(item_ref);
            nested_debug.push({
              "objekt_foto_ref": rel["__key"],
              "item_ref": item_ref,
              "row": rel
            });
          }
        }
        if (nested_debug.length < 1) {
          nested_debug.push({
            "empty": true
          });
        }
      }
      if (item_item_bidi.length > 0) {
        obj[ot][nested_prefix + "item_item_bidi"] = item_item_bidi;
      }
      ref10 = ["item_1314", "item_1333", "item_1272"];
      for (o = 0, len5 = ref10.length; o < len5; o++) {
        nested_suffix = ref10[o];
        if (obj[ot][nested_prefix + nested_suffix] == null) {
          continue;
        }
      }
      if (this.dummy_items[ot] != null) {
        if (this.dummy_items[ot][obj_ref] != null) {
          obj[ot]["lookup:_id"] = {
            "easydb4_reference": obj_ref
          };
          obj[ot]["_version:auto_increment"] = true;
          delete obj[ot]["_version"];
        }
      }
      items.push(obj);
      this.item_references[obj_ref] = ot;
    }
    if (item_fotos.length > 0) {
      new_json = null;
      init_json = (function(_this) {
        return function() {
          return new_json = {
            import_type: "db",
            objecttype: _this.item_foto_ot,
            objects: []
          };
        };
      })(this);
      init_json();
      for (p = 0, len6 = item_fotos.length; p < len6; p++) {
        obj = item_fotos[p];
        new_obj = obj;
        new_obj["_objecttype"] = this.item_foto_ot;
        new_obj[this.item_foto_ot] = obj[ot];
        delete new_obj[ot];
        ref11 = new_obj[this.item_foto_ot];
        for (k in ref11) {
          v = ref11[k];
          if (!k.startsWith(nested_prefix)) {
            continue;
          }
          new_nested_key = k.replace(nested_prefix, "_nested:" + this.item_foto_ot + "__");
          new_obj[this.item_foto_ot][new_nested_key] = v;
          delete new_obj[this.item_foto_ot][k];
        }
        new_json.objects.push(new_obj);
      }
      fn = this.item_foto_ot + "-" + filename_idx + "-" + item_fotos.length + ".json";
      console.debug(this.name(), "| payload_item() | new json:", fn, "with", item_fotos.length, this.item_foto_ot, "objects");
      store_file(fn, new_json, filename_idx);
    }
    if (items.length > 0) {
      new_json = null;
      init_json = (function(_this) {
        return function() {
          return new_json = {
            import_type: "db",
            objecttype: ot,
            objects: items
          };
        };
      })(this);
      init_json();
      fn = ot + "-" + filename_idx + "-" + items.length + ".json";
      console.debug(this.name(), "| payload_item() | new json:", fn, "with", items.length, ot, "objects");
      store_file(fn, new_json, filename_idx);
    }
    json.objects = [];
    if (objekt_foto_objects.length > 0) {
      objekt_foto_json = null;
      init_json = (function(_this) {
        return function() {
          return objekt_foto_json = {
            import_type: "db",
            objecttype: _this.objekt_foto_ot,
            objects: objekt_foto_objects
          };
        };
      })(this);
      init_json();
      fn = this.objekt_foto_ot + "-" + (filename_idx + 1) + "-" + objekt_foto_objects.length + ".json";
      console.debug(this.name(), "| payload_item() | saved", objekt_foto_objects.length, this.objekt_foto_ot, "objects in", fn);
      store_file(fn, objekt_foto_json, filename_idx + 1);
    }
  };

  OrdinariatFreiburg.prototype.payload_tags = function(filename, json) {
    var name, ref, ref1, tags;
    console.debug(this.name(), "| basetype: tags | payload_tags()", filename);
    tags = [];
    ref1 = this.freigabe_tags;
    for (ref in ref1) {
      name = ref1[ref];
      console.debug(this.name(), "tag:", ref, "name:", name);
      tags.push({
        tag: {
          reference: ref,
          displayname: {
            "de-DE": name
          },
          is_default: false,
          enabled: true,
          displaytype: "search",
          type: "individual"
        }
      });
    }
    json.tags.push({
      taggroup: {
        reference: "easydb4:lk_freigabe_id",
        type: "checkbox",
        displayname: {
          "de-DE": "easydb4:lk_freigabe_id"
        }
      },
      _tags: tags
    });
  };

  OrdinariatFreiburg.prototype.payload_tag_freigabe = function(filename, json) {
    var i, len, new_obj, obj, ot, ref1, ref2, tag_ref, updated_objs;
    ot = json.objecttype;
    console.debug(this.name(), "| objecttype:", ot, "| payload_tag_freigabe()", filename);
    updated_objs = [];
    ref1 = json.objects;
    for (i = 0, len = ref1.length; i < len; i++) {
      obj = ref1[i];
      console.debug(this.name(), "| objecttype:", ot, "| payload_tag_freigabe()", obj);
      if (!obj[ot]["_pool"]["pool"]["lookup:_id"]["reference"]) {
        updated_objs.push(obj);
        continue;
      }
      tag_ref = obj[ot]["_pool"]["pool"]["lookup:_id"]["reference"];
      console.debug(this.name(), "| objecttype:", ot, "| payload_tag_freigabe() -> tag_ref:", tag_ref);
      if (!this.freigabe_tags[tag_ref]) {
        delete obj[ot]["_pool"];
        updated_objs.push(obj);
        continue;
      }
      new_obj = obj;
      if (!obj._tags) {
        new_obj._tags = [];
      }
      new_obj._tags.push({
        "lookup:_id": {
          reference: tag_ref
        }
      });
      console.debug(this.name(), "| objecttype:", ot, "| payload_tag_freigabe() -> tags:", obj._tags);
      delete new_obj[ot]["_pool"];
      updated_objs.push(new_obj);
    }
    json.objects = updated_objs;
    if (ref2 = json.objecttype, indexOf.call(this.gnd_field_ots, ref2) >= 0) {
      return this.payload_gnd_links(filename, json);
    }
  };

  OrdinariatFreiburg.prototype.payload_collections = function(filename, json, store_file, filename_idx) {
    var col, i, j, l, len, len1, len2, new_obj, obj, obj_ref, ref1, ref2, ref3, replaced_col_objs, slide;
    console.debug(this.name(), "| payload_collections()", filename);
    ref1 = json.collections;
    for (i = 0, len = ref1.length; i < len; i++) {
      col = ref1[i];
      if (col._objects) {
        console.debug(this.name(), "| collection:", col._objects.length, "objects");
        replaced_col_objs = [];
        ref2 = col._objects;
        for (j = 0, len1 = ref2.length; j < len1; j++) {
          obj = ref2[j];
          if (!obj["lookup:_global_object_id"]) {
            continue;
          }
          if (!obj["lookup:_global_object_id"]["_objecttype"]) {
            continue;
          }
          if (obj["lookup:_global_object_id"]["_objecttype"] !== this.item_ot) {
            replaced_col_objs.push(obj);
            continue;
          }
          if (!obj["lookup:_global_object_id"]["easydb4_reference"]) {
            continue;
          }
          obj_ref = obj["lookup:_global_object_id"]["easydb4_reference"];
          if (!this.item_references[obj_ref]) {
            continue;
          }
          if (this.item_references[obj_ref] === this.item_ot) {
            replaced_col_objs.push(obj);
            continue;
          }
          if (this.item_references[obj_ref] === this.item_foto_ot) {
            new_obj = {
              "lookup:_global_object_id": {
                _objecttype: this.item_foto_ot,
                easydb4_reference: obj_ref
              }
            };
            replaced_col_objs.push(new_obj);
            continue;
          }
        }
        col._objects = replaced_col_objs;
      }
      if (!col.collection) {
        continue;
      }
      if (!col.collection.webfrontend_props) {
        continue;
      }
      if (!col.collection.webfrontend_props.presentation) {
        continue;
      }
      if (!col.collection.webfrontend_props.presentation.slides) {
        continue;
      }
      ref3 = col.collection.webfrontend_props.presentation.slides;
      for (l = 0, len2 = ref3.length; l < len2; l++) {
        slide = ref3[l];
        if (slide.left) {
          slide.left = this.update_slide_gid_lookup(slide.left);
        }
        if (slide.right) {
          slide.right = this.update_slide_gid_lookup(slide.right);
        }
        if (slide.center) {
          slide.center = this.update_slide_gid_lookup(slide.center);
        }
      }
    }
  };

  OrdinariatFreiburg.prototype.update_slide_gid_lookup = function(s) {
    var new_s, obj_ref;
    console.debug(this.name(), "| presentation slide:", s);
    if (!s["lookup:global_object_id"]) {
      return null;
    }
    if (!s["lookup:global_object_id"]["_objecttype"]) {
      return null;
    }
    if (s["lookup:global_object_id"]["_objecttype"] !== this.item_ot) {
      return s;
    }
    if (!s["lookup:global_object_id"]["easydb4_reference"]) {
      return null;
    }
    obj_ref = s["lookup:global_object_id"]["easydb4_reference"];
    if (!this.item_references[obj_ref]) {
      return null;
    }
    if (this.item_references[obj_ref] === this.item_foto_ot) {
      new_s = {
        "lookup:global_object_id": {
          _objecttype: this.item_foto_ot,
          easydb4_reference: obj_ref
        }
      };
      console.debug(this.name(), "| presentation slide object:", obj_ref, "is of type", this.item_foto_ot, "=> switch to", new_s);
      return new_s;
    }
    return s;
  };

  OrdinariatFreiburg.prototype.payload_gnd_links = function(filename, json) {
    var dfr, i, len, obj, object_keys, ot, query, ref1;
    ot = json.objecttype;
    console.debug(this.name(), "| objecttype:", ot, "| payload_gnd_links()", filename);
    object_keys = [];
    ref1 = json.objects;
    for (i = 0, len = ref1.length; i < len; i++) {
      obj = ref1[i];
      if (!obj[ot]) {
        continue;
      }
      if (obj[ot][this.gnd_source_field]) {
        delete obj[ot][this.gnd_source_field];
      }
      if (obj[ot][this.gnd_source_field + ":source_name"]) {
        delete obj[ot][this.gnd_source_field + ":source_name"];
      }
      if (obj[ot]["lookup:" + this.gnd_source_field]) {
        delete obj[ot]["lookup:" + this.gnd_source_field];
      }
      if (obj[ot]["__key"]) {
        object_keys.push(obj[ot]["__key"]);
      }
    }
    dfr = new CUI.Deferred();
    query = ("SELECT id, lk_gnd_normdaten_id\nFROM \"source.public." + ot + "\"\nWHERE id IN ( ") + object_keys.join(", ") + " )\nAND lk_gnd_normdaten_id IS NOT NULL";
    this._migration.query(query).fail(dfr.reject).done((function(_this) {
      return function(result) {
        var j, l, len1, len2, ref2, ref3, row;
        if (result.rows.length > 0) {
          console.debug(_this.name(), "| objecttype:", ot, "| loaded", result.rows.length, "gnd ids for batch");
          ref2 = json.objects;
          for (j = 0, len1 = ref2.length; j < len1; j++) {
            obj = ref2[j];
            if (!obj[ot]["__key"]) {
              continue;
            }
            ref3 = result.rows;
            for (l = 0, len2 = ref3.length; l < len2; l++) {
              row = ref3[l];
              if (obj[ot]["__key"] !== row.id) {
                continue;
              }
              if (!_this.gnd_rows[row.lk_gnd_normdaten_id]) {
                break;
              }
              obj[ot][_this.gnd_target_field] = _this.format_gnd_link(_this.gnd_rows[row.lk_gnd_normdaten_id]);
              break;
            }
          }
        }
        return dfr.resolve();
      };
    })(this));
    return dfr.promise();
  };

  OrdinariatFreiburg.prototype.export_dummy_objects = function(store_file, filename_idx) {
    var batch_offset, dummy_json, dummy_obj, dummy_objects, dummy_ot, fn, init_json, pool_ref, ref, ref1, refs;
    ref1 = this.dummy_items;
    for (dummy_ot in ref1) {
      refs = ref1[dummy_ot];
      dummy_json = null;
      init_json = (function(_this) {
        return function() {
          return dummy_json = {
            import_type: "db",
            objecttype: dummy_ot,
            objects: []
          };
        };
      })(this);
      init_json();
      batch_offset = 1;
      dummy_objects = [];
      for (ref in refs) {
        pool_ref = refs[ref];
        dummy_obj = {
          "_objecttype": dummy_ot,
          "_mask": "_all_fields"
        };
        dummy_obj[dummy_ot] = {
          "_version": 1,
          "easydb4_reference": ref,
          "_pool": {
            "pool": {
              "lookup:_id": {
                "reference": pool_ref
              }
            }
          }
        };
        dummy_json.objects.push(dummy_obj);
        if (dummy_json.objects.length >= 1000) {
          fn = "dummy-" + (filename_idx - 1) + "-" + batch_offset + "-" + dummy_ot + "-" + dummy_json.objects.length + ".json";
          console.debug(this.name(), "| export_dummy_objects() | saved", dummy_json.objects.length, dummy_ot, "objects in", fn);
          store_file(fn, dummy_json, filename_idx - 1);
          dummy_json.objects = [];
          batch_offset++;
        }
      }
      if (dummy_json.objects.length > 0) {
        fn = "dummy-" + (filename_idx - 1) + "-" + batch_offset + "-" + dummy_ot + "-" + dummy_json.objects.length + ".json";
        console.debug(this.name(), "| export_dummy_objects() | saved", dummy_json.objects.length, dummy_ot, "objects in", fn);
        store_file(fn, dummy_json, filename_idx - 1);
      }
    }
  };

  OrdinariatFreiburg.prototype.format_item_item_typ = function(name) {
    var obj;
    obj = {
      "_objecttype": this.item_item_typ_ot,
      "_mask": "_all_fields"
    };
    obj[this.item_item_typ_ot] = {
      "_version": 1,
      "name": name
    };
    return obj;
  };

  OrdinariatFreiburg.prototype.link_item_item_typ = function(name) {
    var obj;
    obj = {
      "_objecttype": this.item_item_typ_ot,
      "_mask": "_all_fields"
    };
    obj[this.item_item_typ_ot] = {
      "lookup:_id": {
        "name": name
      }
    };
    return obj;
  };

  OrdinariatFreiburg.prototype.create_item_item_typ_objects = function(store_file, filename_idx) {
    var dummy_json, fn, init_json, link;
    dummy_json = null;
    init_json = (function(_this) {
      return function() {
        return dummy_json = {
          import_type: "db",
          objecttype: _this.item_item_typ_ot,
          objects: []
        };
      };
    })(this);
    init_json();
    link = this.format_item_item_typ(this.item_item_typ__ist_kind_von);
    link[this.item_item_typ_ot]["_version"] = 2;
    link[this.item_item_typ_ot]["lookup:_id"] = {
      "name": this.item_item_typ__ist_kind_von
    };
    link[this.item_item_typ_ot]["zugehoeriger_typ"] = this.link_item_item_typ(this.item_item_typ__hat_kind);
    dummy_json.objects.push(link);
    link = this.format_item_item_typ(this.item_item_typ__hat_kind);
    link[this.item_item_typ_ot]["_version"] = 2;
    link[this.item_item_typ_ot]["lookup:_id"] = {
      "name": this.item_item_typ__hat_kind
    };
    link[this.item_item_typ_ot]["zugehoeriger_typ"] = this.link_item_item_typ(this.item_item_typ__ist_kind_von);
    dummy_json.objects.push(link);
    fn = "new-" + (filename_idx - 1) + "-version-2-" + this.item_item_typ_ot + "-" + dummy_json.objects.length + ".json";
    console.debug(this.name(), "| create_item_item_typ_objects() | saved", dummy_json.objects.length, this.item_item_typ_ot, "objects in", fn);
    store_file(fn, dummy_json, filename_idx - 1);
    init_json();
    dummy_json.objects.push(this.format_item_item_typ(this.item_item_typ__ist_kind_von));
    dummy_json.objects.push(this.format_item_item_typ(this.item_item_typ__hat_kind));
    fn = "new-" + (filename_idx - 1) + "-version-1-" + this.item_item_typ_ot + "-" + dummy_json.objects.length + ".json";
    console.debug(this.name(), "| create_item_item_typ_objects() | saved", dummy_json.objects.length, this.item_item_typ_ot, "objects in", fn);
    store_file(fn, dummy_json, filename_idx - 1);
  };

  OrdinariatFreiburg.prototype.payload = function(filename, json, update, store_file, filename_idx) {
    var ref1;
    if (json.import_type === "tags") {
      return this.payload_tags(filename, json);
    }
    if (json.import_type === "collection") {
      return this.payload_collections(filename, json, store_file, filename_idx);
    }
    if (json.import_type !== "db") {
      return;
    }
    if (!this.dummys_exported) {
      this.export_dummy_objects(store_file, filename_idx);
      this.dummys_exported = true;
    }
    if (!this.item_item_typ_created) {
      this.create_item_item_typ_objects(store_file, filename_idx);
      this.item_item_typ_created = true;
    }
    if (json.objecttype === this.item_ot) {
      return this.payload_item(filename, json, store_file, filename_idx);
    }
    if (json.objecttype === "publikation" || json.objecttype === "archivalie") {
      return this.payload_tag_freigabe(filename, json);
    }
    if (ref1 = json.objecttype, indexOf.call(this.gnd_field_ots, ref1) >= 0) {
      return this.payload_gnd_links(filename, json);
    }
  };

  return OrdinariatFreiburg;

})(Easydb4MigrationPlugin);

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