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

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

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

  EthZuerich.prototype.name = function() {
    return "eth-zuerich";
  };

  EthZuerich.prototype.chunkSize = 10000;

  EthZuerich.prototype.payload = function(filename, json, update, store_file) {
    if (filename.startsWith("Bilder-")) {
      return this.payloadBilder(filename, json, update, store_file);
    }
  };

  EthZuerich.prototype.payloadBilder = function(filename, json, update, store_file) {
    var i, j, k, kuenstler, l, len1, len2, len3, len4, lookup, obj, ort, ref, ref1, ref2, ref3, ref4, standort;
    ref1 = json.objects;
    for (i = 0, len1 = ref1.length; i < len1; i++) {
      obj = ref1[i];
      ref2 = obj.bilder["_nested:bilder__bilder__kuenstler_getty"] || [];
      for (j = 0, len2 = ref2.length; j < len2; j++) {
        kuenstler = ref2[j];
        if (!kuenstler["lookup:lk_person_id"]) {
          continue;
        }
        ref = kuenstler["lookup:lk_person_id"].__not_found_easydb4_reference;
        lookup = {
          _objecttype: "personen",
          _mask: "_all_fields",
          personen: {
            "lookup:_id": {
              easydb4_reference: ref
            }
          }
        };
        kuenstler["lk_person_id"] = lookup;
        delete kuenstler["lookup:lk_person_id"];
      }
      ref3 = obj.bilder["_nested:bilder__bilder__standort_getty"] || [];
      for (k = 0, len3 = ref3.length; k < len3; k++) {
        standort = ref3[k];
        if (!standort["lookup:lk_ort_id"]) {
          continue;
        }
        ref = standort["lookup:lk_ort_id"].__not_found_easydb4_reference;
        lookup = {
          _objecttype: "orte",
          _mask: "_all_fields",
          orte: {
            "lookup:_id": {
              easydb4_reference: ref
            }
          }
        };
        standort["lk_ort_id"] = lookup;
        delete standort["lookup:lk_ort_id"];
      }
      ref4 = obj.bilder["_nested:bilder__bilder__ort_getty"] || [];
      for (l = 0, len4 = ref4.length; l < len4; l++) {
        ort = ref4[l];
        if (!ort["lookup:lk_ort_id"]) {
          continue;
        }
        ref = ort["lookup:lk_ort_id"].__not_found_easydb4_reference;
        lookup = {
          _objecttype: "orte",
          _mask: "_all_fields",
          orte: {
            "lookup:_id": {
              easydb4_reference: ref
            }
          }
        };
        ort["lk_ort_id"] = lookup;
        delete ort["lookup:lk_ort_id"];
      }
    }
  };

  EthZuerich.prototype.payloadGetty = function(store_file) {
    var dfr;
    dfr = new CUI.Deferred();
    this._migration.query("SELECT COUNT(id) AS count FROM \"source.public.getty_subject\" WHERE lk_easydb_vocabulary_id = 1").fail(dfr.reject).done((function(_this) {
      return function(result) {
        var orte_count;
        orte_count = result.rows[0].count;
        return _this._migration.query("SELECT COUNT(id) AS count FROM \"source.public.getty_subject\" WHERE lk_easydb_vocabulary_id = 2").fail(dfr.reject).done(function(result) {
          var personen_count;
          personen_count = result.rows[0].count;
          if (false) {
            personen_count = 1000;
            orte_count = 1000;
          }
          orte_count = 0;
          console.debug("Orte: ", orte_count, "Personen:", personen_count);
          return _this.export_orte(store_file, orte_count).fail(dfr.reject).done(function() {
            return _this.export_personen(store_file, personen_count).done(dfr.resolve).fail(dfr.reject);
          });
        });
      };
    })(this));
    return dfr.promise();
  };

  EthZuerich.prototype.export_personen = function(store_file, personen_limit) {
    var faked_arr, promise, update_payloads;
    faked_arr = [];
    faked_arr[personen_limit - 1] = true;
    update_payloads = [];
    promise = CUI.chunkWork.call(this, {
      items: faked_arr,
      chunk_size: this.chunkSize,
      call: (function(_this) {
        return function(faked_items, offset, len) {
          var dfr, limit, range, splash_text;
          limit = faked_items.length;
          range = (offset + 1) + "-" + Math.min(limit + offset, len);
          splash_text = "getty_subject/personen " + range + "/" + len;
          ez5.splash.show("easydb4migration.progress", {
            payload: splash_text
          });
          dfr = new CUI.Deferred();
          _this._migration.query(_this.sql(2, offset, limit)).fail(dfr.reject).done(function(result) {
            var current_bio_id, current_id, current_term_id, first_term_id, i, len1, obj, payload, ref1, row;
            payload = {
              import_type: "db",
              objecttype: "personen",
              objects: []
            };
            current_id = null;
            ref1 = result.rows;
            for (i = 0, len1 = ref1.length; i < len1; i++) {
              row = ref1[i];
              if (row.digitale_diathek_id !== current_id) {
                current_id = row.digitale_diathek_id;
                current_term_id = null;
                first_term_id = null;
                current_bio_id = null;
                obj = {
                  _objecttype: "personen",
                  _mask: "_all_fields",
                  personen: {
                    _version: 1,
                    digitale_diathek_id: current_id,
                    easydb4_reference: row.easydb4_reference,
                    getty_id: row.getty_id,
                    gnd_id: row.gnd_id,
                    viaf_id: row.viaf_id,
                    preferred_term: {
                      "en-US": row.easydb_getty_term_preferred_text
                    },
                    "_nested:personen__terms": [],
                    "_nested:personen__biographies": []
                  }
                };
                payload.objects.push(obj);
              }
              if (current_term_id !== row.easydb_term_id) {
                if (!first_term_id) {
                  first_term_id = row.easydb_term_id;
                }
                current_term_id = row.easydb_term_id;
                if (row.term_preferred) {
                  obj.personen.preferred_term = {
                    "en-US": row.term_text
                  };
                  obj.personen.getty_link = _this.getty_link("ulan", row.getty_id, row.term_text);
                  obj.personen.gnd_link = _this.gnd_link(row.gnd_id, row.term_text);
                }
                obj.personen["_nested:personen__terms"].push({
                  term: row.term_text,
                  _display_order: row._display_order,
                  preferred: row.term_preferred ? true : false,
                  language: _this.lang_link(row.term_getty_language)
                });
                obj.personen["_nested:personen__terms"].sort(function(a, b) {
                  return CUI.util.compareIndex(a._display_order, b._display_order);
                });
              }
              if (current_bio_id !== row.easydb_bio_id && row.easydb_term_id === first_term_id) {
                current_bio_id = row.easydb_bio_id;
                if (row.bio_preferred || !current_bio_id) {
                  obj.personen.preferred_biography = {
                    "en-US": row.biography
                  };
                }
                obj.personen["_nested:personen__biographies"].push({
                  biography: row.biography,
                  preferred: row.bio_preferred ? true : false
                });
              }
              if (row.easydb4_reference_birth_place) {
                obj.personen.birth_place = {
                  _objecttype: "orte",
                  _mask: "_all_fields",
                  _depth: row._depth,
                  orte: {
                    "lookup:_id": {
                      easydb4_reference: row.easydb4_reference_birth_place
                    }
                  }
                };
              }
              if (row.easydb4_reference_death_place) {
                obj.personen.death_place = {
                  _objecttype: "orte",
                  _mask: "_all_fields",
                  orte: {
                    "lookup:_id": {
                      easydb4_reference: row.easydb4_reference_death_place
                    }
                  }
                };
              }
            }
            store_file("personen-" + range + ".json", payload).done(dfr.resolve).fail(dfr.reject);
          });
          return dfr.promise();
        };
      })(this)
    }).done((function(_this) {
      return function() {
        return console.debug("getty_subject/personen done.");
      };
    })(this));
    return promise;
  };

  EthZuerich.prototype.export_orte = function(store_file, orte_limit) {
    var faked_arr, promise;
    faked_arr = [];
    faked_arr[orte_limit - 1] = true;
    promise = CUI.chunkWork.call(this, {
      items: faked_arr,
      chunk_size: this.chunkSize,
      call: (function(_this) {
        return function(faked_items, offset, len) {
          var dfr, limit, range, splash_text;
          limit = faked_items.length;
          range = (offset + 1) + "-" + Math.min(limit + offset, len);
          splash_text = "getty_subject/orte " + range + "/" + len;
          ez5.splash.show("easydb4migration.progress", {
            payload: splash_text
          });
          dfr = new CUI.Deferred();
          _this._migration.query(_this.sql(1, offset, limit)).fail(dfr.reject).done(function(result) {
            var current_id, current_term_id, i, idx, j, len1, len2, obj, payload, payloads, promises, ref1, row;
            current_id = null;
            payloads = [];
            ref1 = result.rows;
            for (i = 0, len1 = ref1.length; i < len1; i++) {
              row = ref1[i];
              if (row.digitale_diathek_id !== current_id) {
                current_id = row.digitale_diathek_id;
                current_term_id = null;
                obj = {
                  _objecttype: "orte",
                  _mask: "_all_fields",
                  _depth: row._depth,
                  orte: {
                    _version: 1,
                    digitale_diathek_id: current_id,
                    easydb4_reference: row.easydb4_reference,
                    getty_id: row.getty_id,
                    gnd_id: row.gnd_id,
                    viaf_id: row.viaf_id,
                    preferred_term: {
                      "en-US": row.easydb_getty_term_preferred_text
                    },
                    "_nested:orte__terms": []
                  }
                };
                if (row.easydb4_reference_parent) {
                  obj.orte["lookup:_id_parent"] = {
                    easydb4_reference: row.easydb4_reference_parent
                  };
                }
                payload = payloads[obj._depth];
                if (!payload) {
                  payload = payloads[obj._depth] = {
                    import_type: "db",
                    objecttype: "orte",
                    objects: []
                  };
                }
                payload.objects.push(obj);
              }
              if (row.term_preferred) {
                obj.orte.preferred_term = {
                  "en-US": row.term_text
                };
                obj.orte.getty_link = _this.getty_link("tgn", row.getty_id, row.term_text);
                obj.orte.gnd_link = _this.gnd_link(row.gnd_id, row.term_text);
              }
              current_term_id = row.easydb_term_id;
              obj.orte["_nested:orte__terms"].push({
                term: row.term_text,
                _display_order: row.display_order || 99,
                preferred: row.term_preferred ? true : false,
                language: _this.lang_link(row.term_getty_language)
              });
              obj.orte["_nested:orte__terms"].sort(function(a, b) {
                return CUI.util.compareIndex(a._display_order, b._display_order);
              });
            }
            promises = [];
            for (idx = j = 0, len2 = payloads.length; j < len2; idx = ++j) {
              payload = payloads[idx];
              if (!payload) {
                continue;
              }
              promises.push(store_file("orte-level-" + idx + "-" + range + ".json", payload));
            }
            CUI.when(promises).done(dfr.resolve).fail(dfr.reject);
          });
          return dfr.promise();
        };
      })(this)
    }).done((function(_this) {
      return function() {
        return console.debug("getty_subject/orte done.");
      };
    })(this));
    return promise;
  };

  EthZuerich.prototype.lang_link = function(lang_ref) {
    var link;
    if (!lang_ref) {
      return void 0;
    }
    link = {
      _objecttype: "sprachen",
      _mask: "_all_fields",
      sprachen: {
        "lookup:_id": {
          easydb4_reference: lang_ref
        }
      }
    };
    return link;
  };

  EthZuerich.prototype.getty_link = function(catalog, subject_id, term) {
    var link;
    if (!subject_id) {
      return void 0;
    }
    link = {
      conceptName: term,
      conceptURI: "http://vocab.getty.edu/" + catalog + "/" + subject_id,
      _fulltext: {
        text: term,
        string: term
      },
      _standard: {
        text: term
      }
    };
    return link;
  };

  EthZuerich.prototype.gnd_link = function(gnd_id, term) {
    var link;
    if (!gnd_id) {
      return void 0;
    }
    link = {
      conceptName: term,
      conceptURI: "http://d-nb.info/gnd/" + gnd_id,
      _fulltext: {
        text: term,
        string: term
      },
      _standard: {
        text: term
      }
    };
    return link;
  };

  EthZuerich.prototype.sql = function(voc_id, offset, limit) {
    var off_limit, sql;
    if (limit > 0) {
      off_limit = "LIMIT " + limit;
    } else {
      off_limit = "LIMIT -1";
    }
    off_limit += " OFFSET " + offset;
    sql = "WITH RECURSIVE ids AS (\n    SELECT id, 0 as level, lk_easydb_vocabulary_id\n    FROM \"source.public.getty_subject\"\n	WHERE lk_easydb_vocabulary_id = " + voc_id + " AND fk_father_id IS NULL\nUNION ALL\n    SELECT a.id, ids.level + 1, a.lk_easydb_vocabulary_id\n    FROM \"source.public.getty_subject\" a\n    JOIN ids ON (a.fk_father_id = ids.id)\n)\n,\nids2 AS (SELECT * FROM ids ORDER BY level, id " + off_limit + ")\n\nSELECT\n   level as _depth,\n   a.id as digitale_diathek_id,\n   a.getty_subject_id as getty_id,\n   \"getty_subject:\" || a.fk_father_id as easydb4_reference_parent,\n   \"getty_subject:\" || a.id as easydb4_reference,\n   a.viaf_id,\n   a.gnd_id,\n   a.easydb_getty_term_preferred_text,\n   b.id AS easydb_term_id,\n   b.getty_term_id,\n   b.term_text,\n   b.display_order,\n   b.preferred AS term_preferred,\n   \"getty_language:\" || d.id as term_getty_language,\n   d.getty_language_name,\n   e.id as easydb_bio_id,\n   e.preferred AS bio_preferred,\n   e.biography,\n   \"getty_subject:\" || e.birth_place as easydb4_reference_birth_place,\n   \"getty_subject:\" || e.death_place as easydb4_reference_death_place\n   FROM ids2 z\n   LEFT JOIN \"source.public.getty_subject\" a ON (z.id = a.id)\n   LEFT JOIN \"source.public.getty_term\" b ON (b.lk_getty_subject_id = a.id)\n   LEFT JOIN \"source.public.getty_term__getty_language\" c ON (c.lk_getty_term_id = b.id)\n   LEFT JOIN \"source.public.getty_language\" d ON (c.lk_getty_language_id = d.id)\n   LEFT JOIN \"source.public.getty_biography\" e ON (e.lk_getty_subject_id = a.id)\n\nORDER BY a.id, b.id, e.id";
    console.debug("SQL:", sql);
    return sql;
  };

  return EthZuerich;

})(Easydb4MigrationPlugin);

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