// Generated by CoffeeScript 2.3.2
(function() {
  var ByField, ConfigNode;

  ({ConfigNode} = require("@l.degener/irma-config"));

  module.exports = ByField = class ByField extends ConfigNode {
    constructor(options, direction) {
      super(options);
      this.directionString = direction != null ? direction : 'asc';
      if (options.prefixField != null) {
        this.aggregation = function() {
          return {
            terms: {
              field: options.prefixField,
              size: 0
            }
          };
        };
        this.interpreteAggResult = function(body) {
          var acc, bucket, buckets, d, i, len, ref, sections;
          d = this.directionString;
          buckets = ((ref = body != null ? body.buckets : void 0) != null ? ref : []).sort(function(a, b) {
            if ('asc' === d) {
              return a.key.localeCompare(b.key);
            } else {
              return b.key.localeCompare(a.key);
            }
          });
          sections = {};
          acc = 0;
          for (i = 0, len = buckets.length; i < len; i++) {
            bucket = buckets[i];
            sections[bucket.key] = {
              start: acc,
              length: bucket.doc_count,
              end: acc + bucket.doc_count
            };
            acc += bucket.doc_count;
          }
          return sections;
        };
      }
    }

    direction(string) {
      if (string != null) {
        return new ByField(this._options, string);
      } else {
        return this.directionString;
      }
    }

    sort() {
      var direction, fields, ref, ref1;
      direction = this.directionString;
      fields = (ref = (ref1 = this._options.fields) != null ? ref1.slice(0) : void 0) != null ? ref : [];
      if (this._options.field) {
        fields.unshift(this._options.field);
      }
      if (fields.length === 1) {
        return {
          [`${fields[0]}`]: direction
        };
      } else {
        return fields.map(function(field) {
          return {
            [`${field}`]: direction
          };
        });
      }
    }

  };

}).call(this);
