// Generated by CoffeeScript 1.12.7
var DANTE_ListViewTree, DANTE_ListViewTreeNode,
  bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  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; };

DANTE_ListViewTree = (function() {
  function DANTE_ListViewTree(popover, editor_layout, cdata, cdata_form, context, dante_opts, vocParameter) {
    var column, options, row, that, treeview;
    this.popover = popover != null ? popover : null;
    this.editor_layout = editor_layout != null ? editor_layout : null;
    this.cdata = cdata != null ? cdata : null;
    this.cdata_form = cdata_form != null ? cdata_form : null;
    this.context = context != null ? context : null;
    this.dante_opts = dante_opts != null ? dante_opts : {};
    this.vocParameter = vocParameter != null ? vocParameter : 'test';
    options = {
      "class": "dantePlugin_Treeview",
      cols: ["maximize", "auto"],
      fixedRows: 0,
      fixedCols: 0,
      no_hierarchy: false
    };
    that = this;
    treeview = new CUI.ListViewTree(options);
    treeview.render();
    treeview.root.open();
    row = new CUI.ListViewRow();
    column = new CUI.ListViewColumn({
      colspan: 2,
      element: new CUI.Label({
        icon: "spinner",
        appearance: "title",
        text: $$("custom.data.type.dante.modal.form.popup.loadingstringtreeview")
      })
    });
    row.addColumn(column);
    treeview.appendRow(row);
    treeview.root.open();
    this.treeview = treeview;
    this.treeview;
  }

  DANTE_ListViewTree.prototype.getTopTreeView = function(vocName, cache) {
    var dfr, that, topTree_xhr, url;
    if (cache == null) {
      cache = 1;
    }
    dfr = new CUI.Deferred();
    that = this;
    topTree_xhr = {
      "xhr": void 0
    };
    if (cache !== 1 && cache !== 0) {
      cache = 1;
    }
    url = location.protocol + '//api.dante.gbv.de/voc/' + vocName + '/top?format=json&properties=+notation&limit=100&cache=' + cache;
    topTree_xhr.xhr = new CUI.XHR({
      url: url
    });
    topTree_xhr.xhr.start().done(function(data, status, statusText) {
      var hasNarrowers, i, jskos, key, len, newNode, prefLabel, ref;
      if (that.treeview.getRow(0)) {
        that.treeview.removeRow(0);
      }
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        jskos = data[key];
        prefLabel = CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(jskos);
        if (((ref = jskos.narrower) != null ? ref.length : void 0) > 0) {
          hasNarrowers = true;
        } else {
          hasNarrowers = false;
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          prefLabel: prefLabel,
          uri: jskos.uri,
          hasNarrowers: hasNarrowers,
          popover: that.popover,
          cdata: that.cdata,
          cdata_form: that.cdata_form,
          guideTerm: DANTE_ListViewTreeNode.prototype.isGuideTerm(jskos),
          context: that.context,
          vocParameter: that.vocParameter,
          dante_opts: that.dante_opts,
          editor_layout: that.editor_layout
        });
        that.treeview.addNode(newNode);
      }
      CUI.Events.trigger({
        node: that.popover,
        type: "content-resize"
      });
      dfr.resolve();
      return dfr.promise();
    });
    return dfr;
  };

  DANTE_ListViewTree.prototype.getSearchResultTree = function(searchTerm, vocName, cache) {
    var dfr, searchTree_xhr, that, url;
    if (cache == null) {
      cache = 1;
    }
    dfr = new CUI.Deferred();
    that = this;
    searchTree_xhr = {
      "xhr": void 0
    };
    url = location.protocol + '//api.dante.gbv.de/search?voc=' + vocName + '&query=' + searchTerm + '&format=json&limit=100&cache=' + cache + '&properties=+ancestors,notation&offset=0';
    searchTree_xhr.xhr = new CUI.XHR({
      url: url
    });
    searchTree_xhr.xhr.start().done(function(data, status, statusText) {
      var addToVirtualTree, ancestorLevel, ancestorValue, children, childrenCount, counter, getChildNodesFromVirtualTree, hasNarrowers, i, itselfAsAncestor, j, jskos, key, len, len1, maxCount, newNode, node, ref, value, virtualTree;
      that.treeview.removeAllRows();
      virtualTree = [];
      counter = 0;
      maxCount = 10000;
      addToVirtualTree = function(treePart, newNode, parentUri) {
        var nodeKey, nodeValue;
        if (counter > maxCount) {
          exit;
        }
        for (nodeKey in treePart) {
          nodeValue = treePart[nodeKey];
          if (nodeKey === parentUri) {
            if (!nodeValue['children'][newNode.uri]) {
              nodeValue['children'][newNode.uri] = newNode;
            }
            return;
          } else {
            addToVirtualTree(nodeValue['children'], newNode, parentUri);
          }
        }
      };
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        value = data[key];
        if (data[key] !== null) {
          jskos = value;
          itselfAsAncestor = {
            prefLabel: jskos.prefLabel,
            uri: jskos.uri,
            type: jskos.type
          };
          jskos.ancestors.unshift(itselfAsAncestor);
          if (jskos.ancestors.length > 0) {
            jskos.ancestors = jskos.ancestors.reverse();
            ref = jskos.ancestors;
            for (ancestorLevel = j = 0, len1 = ref.length; j < len1; ancestorLevel = ++j) {
              ancestorValue = ref[ancestorLevel];
              node = {
                prefLabel: CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(ancestorValue),
                uri: ancestorValue.uri,
                guideTerm: DANTE_ListViewTreeNode.prototype.isGuideTerm(ancestorValue),
                children: {}
              };
              if (ancestorLevel === 0) {
                if (!virtualTree[ancestorValue.uri]) {
                  virtualTree[ancestorValue.uri] = node;
                }
              } else if (ancestorLevel > 0) {
                addToVirtualTree(virtualTree, node, jskos.ancestors[ancestorLevel - 1].uri);
              }
            }
          }
        }
      }
      counter = 0;
      getChildNodesFromVirtualTree = function(treePart) {
        var childrenCount, hasNarrowers, newNode, nodeKey, nodeValue, nodes;
        nodes = [];
        counter++;
        if (counter > maxCount) {
          exit;
        }
        for (nodeKey in treePart) {
          nodeValue = treePart[nodeKey];
          childrenCount = Object.keys(nodeValue.children).length;
          hasNarrowers = childrenCount > 0 ? true : false;
          newNode = new DANTE_ListViewTreeNode({
            selectable: false,
            open: hasNarrowers,
            children: getChildNodesFromVirtualTree(nodeValue.children),
            prefLabel: nodeValue.prefLabel,
            uri: nodeValue.uri,
            vocParameter: that.vocParameter,
            hasNarrowers: hasNarrowers,
            guideTerm: nodeValue.guideTerm,
            popover: that.popover,
            cdata: that.cdata,
            cdata_form: that.cdata_form,
            context: that.context,
            dante_opts: that.dante_opts,
            editor_layout: that.editor_layout
          });
          nodes.push(newNode);
        }
        return nodes;
      };
      for (key in virtualTree) {
        value = virtualTree[key];
        childrenCount = Object.keys(value.children).length;
        hasNarrowers = childrenCount > 0 ? true : false;
        children = [];
        if (hasNarrowers) {
          children = getChildNodesFromVirtualTree(value.children);
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          open: hasNarrowers,
          hasChildren: hasNarrowers,
          children: children,
          prefLabel: value.prefLabel,
          uri: value.uri,
          vocParameter: that.vocParameter,
          hasNarrowers: hasNarrowers,
          guideTerm: value.guideTerm,
          popover: that.popover,
          cdata: that.cdata,
          cdata_form: that.cdata_form,
          context: that.context,
          dante_opts: that.dante_opts,
          editor_layout: that.editor_layout
        });
        that.treeview.addNode(newNode);
      }
      dfr.resolve();
      return dfr.promise();
    });
    return dfr;
  };

  return DANTE_ListViewTree;

})();

DANTE_ListViewTreeNode = (function(superClass) {
  var prefLabel, uri;

  extend(DANTE_ListViewTreeNode, superClass);

  function DANTE_ListViewTreeNode() {
    this.renderContent = bind(this.renderContent, this);
    this.isLeaf = bind(this.isLeaf, this);
    this.getChildren = bind(this.getChildren, this);
    this.isGuideTerm = bind(this.isGuideTerm, this);
    return DANTE_ListViewTreeNode.__super__.constructor.apply(this, arguments);
  }

  prefLabel = '';

  uri = '';

  DANTE_ListViewTreeNode.prototype.initOpts = function() {
    DANTE_ListViewTreeNode.__super__.initOpts.call(this);
    return this.addOpts({
      prefLabel: {
        check: String
      },
      uri: {
        check: String
      },
      vocParameter: {
        check: String
      },
      children: {
        check: Array
      },
      guideTerm: {
        check: Boolean,
        "default": false
      },
      hasNarrowers: {
        check: Boolean,
        "default": false
      },
      popover: {
        check: CUI.Popover
      },
      cdata: {
        check: "PlainObject",
        "default": {}
      },
      cdata_form: {
        check: CUI.Form
      },
      context: {
        check: CustomDataTypeDANTE
      },
      dante_opts: {
        check: "PlainObject",
        "default": {}
      },
      editor_layout: {
        check: CUI.HorizontalLayout
      }
    });
  };

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

  DANTE_ListViewTreeNode.prototype.isGuideTerm = function(jskos) {
    if (indexOf.call(jskos.type, 'http://vocab.getty.edu/ontology#GuideTerm') >= 0) {
      return true;
    } else {
      return false;
    }
  };

  DANTE_ListViewTreeNode.prototype.getChildren = function() {
    var cache, children, dfr, getChildren_xhr, that, url;
    that = this;
    dfr = new CUI.Deferred();
    children = [];
    cache = '1';
    if (that._context.resettedPopup) {
      cache = '0';
    }
    url = location.protocol + '//api.dante.gbv.de/narrower?format=json&uri=' + this._uri + '&limit=100&cache=' + cache + '&voc=' + this._vocParameter;
    getChildren_xhr = {
      "xhr": void 0
    };
    getChildren_xhr.xhr = new CUI.XHR({
      url: url
    });
    getChildren_xhr.xhr.start().done(function(data, status, statusText) {
      var hasNarrowers, i, jskos, key, len, newNode, ref;
      for (key = i = 0, len = data.length; i < len; key = ++i) {
        jskos = data[key];
        prefLabel = CustomDataTypeDANTE.prototype.getPrefLabelFromJSKOS(jskos);
        if (((ref = jskos.narrower) != null ? ref.length : void 0) > 0) {
          hasNarrowers = true;
        } else {
          hasNarrowers = false;
        }
        newNode = new DANTE_ListViewTreeNode({
          selectable: false,
          prefLabel: prefLabel,
          uri: jskos.uri,
          vocParameter: that._vocParameter,
          hasNarrowers: hasNarrowers,
          popover: that._popover,
          cdata: that._cdata,
          cdata_form: that._cdata_form,
          guideTerm: that.isGuideTerm(jskos),
          context: that._context,
          dante_opts: that._dante_opts,
          editor_layout: that._editor_layout
        });
        children.push(newNode);
      }
      return dfr.resolve(children);
    });
    return dfr.promise();
  };

  DANTE_ListViewTreeNode.prototype.isLeaf = function() {
    if (this.opts.hasNarrowers === true) {
      return false;
    } else {
      return true;
    }
  };

  DANTE_ListViewTreeNode.prototype.renderContent = function() {
    var buttonBar, buttons, d, extendedInfo_xhr, icon, infoButton, plusButton, that, tooltipText;
    that = this;
    extendedInfo_xhr = {
      "xhr": void 0
    };
    d = CUI.dom.div();
    buttons = [];
    icon = 'fa-plus-circle';
    tooltipText = $$('custom.data.type.dante.modal.form.popup.add_choose');
    if (that._guideTerm) {
      icon = 'fa-sitemap';
      tooltipText = $$('custom.data.type.dante.modal.form.popup.add_sitemap');
    }
    plusButton = new CUI.Button({
      text: "",
      icon_left: new CUI.Icon({
        "class": icon
      }),
      active: false,
      group: "default",
      tooltip: {
        text: tooltipText
      },
      onClick: (function(_this) {
        return function() {
          var allDataAPIPath, cache, dataEntry_xhr;
          cache = '&cache=0';
          if (that._context.resettedPopup) {
            cache = '&cache=1';
          }
          allDataAPIPath = location.protocol + '//api.dante.gbv.de/data?uri=' + that._uri + cache + '&properties=+ancestors';
          dataEntry_xhr = new CUI.XHR({
            url: allDataAPIPath
          });
          return dataEntry_xhr.start().done(function(data_response, status, statusText) {
            var i, jskos, len, ref, ref1, ref2, ref3, ref4, ref5, ref6, resultJSKOS;
            resultJSKOS = data_response[0];
            that._cdata.conceptAncestors = [];
            if (resultJSKOS.ancestors.length > 0) {
              ref = resultJSKOS.ancestors;
              for (i = 0, len = ref.length; i < len; i++) {
                jskos = ref[i];
                that._cdata.conceptAncestors.push(jskos.uri);
              }
            }
            that._cdata.conceptAncestors.push(that._uri);
            that._cdata.conceptAncestors = that._cdata.conceptAncestors.join(' ');
            if (((ref1 = that._context) != null ? (ref2 = ref1.FieldSchema) != null ? (ref3 = ref2.custom_settings) != null ? (ref4 = ref3.allow_label_choice) != null ? ref4.value : void 0 : void 0 : void 0 : void 0) === true && ((ref5 = that._dante_opts) != null ? ref5.mode : void 0) === 'editor') {
              CustomDataTypeDANTE.prototype.__chooseLabelManually(that._cdata, that._editor_layout, resultJSKOS, that._editor_layout, that._dante_opts);
            }
            that._cdata.conceptName = that._prefLabel;
            that._cdata.conceptURI = that._uri;
            that._cdata._fulltext = ez5.DANTEUtil.getFullTextFromJSKOSObject(resultJSKOS);
            that._cdata._standard = ez5.DANTEUtil.getStandardFromJSKOSObject(resultJSKOS);
            that._cdata.facetTerm = ez5.DANTEUtil.getFacetTermFromJSKOSObject(resultJSKOS);
            if (((ref6 = that._dante_opts) != null ? ref6.callFromExpertSearch : void 0) === true) {
              CustomDataTypeDANTE.prototype.__chooseExpertHierarchicalSearchMode(that._cdata, that._editor_layout, resultJSKOS, that._editor_layout, that._dante_opts);
            }
            CustomDataTypeDANTE.prototype.__updateResult(that._cdata, that._editor_layout, that._dante_opts);
            return that._popover.hide();
          });
        };
      })(this)
    });
    plusButton.setEnabled(!that._guideTerm);
    buttons.push(plusButton);
    infoButton = new CUI.Button({
      text: "",
      icon_left: new CUI.Icon({
        "class": "fa-info-circle"
      }),
      active: false,
      group: "default",
      tooltip: {
        markdown: true,
        placement: "e",
        content: function(tooltip) {
          CustomDataTypeDANTE.prototype.__getAdditionalTooltipInfo(that._uri, tooltip, extendedInfo_xhr, that._context);
          return new CUI.Label({
            icon: "spinner",
            text: $$('custom.data.type.dante.modal.form.popup.loadingstring')
          });
        }
      }
    });
    buttons.push(infoButton);
    buttonBar = new CUI.Buttonbar({
      buttons: buttons
    });
    CUI.dom.append(d, CUI.dom.append(CUI.dom.div(), buttonBar.DOM));
    this.addColumn(new CUI.ListViewColumn({
      element: d,
      colspan: 1
    }));
    CUI.Events.trigger({
      node: that._popover,
      type: "content-resize"
    });
    return new CUI.Label({
      text: this._prefLabel
    });
  };

  return DANTE_ListViewTreeNode;

})(CUI.ListViewTreeNode);
