// Generated by CoffeeScript 2.3.2
(function() {
  var CompositeQuery, ConfigNode, collectClauses, empty, flatmap, occurences,
    indexOf = [].indexOf;

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

  flatmap = function(arr, f) {
    var reducer;
    reducer = function(out, elm, i, arr) {
      return out.concat(f(elm, i, arr));
    };
    return arr.reduce(reducer, []);
  };

  empty = function(a) {
    switch (false) {
      case !(a == null):
        return true;
      case !Array.isArray(a):
        return a.length === 0;
      case typeof a !== "object":
        switch (false) {
          case Object.keys(a).length !== 0:
            return true;
          case !(Object.keys(a).length === 1 && (a.match_all != null)):
            return true;
          default:
            return false;
        }
        break;
      case typeof a !== "string":
        return a.trim().length === 0;
      default:
        return false;
    }
  };

  collectClauses = function(occurence, options, args) {
    var clauses, components, ref;
    components = (ref = options[occurence]) != null ? ref : [];
    if (!Array.isArray(components)) {
      components = [components];
    }
    clauses = flatmap(components, function(cmp) {
      return cmp.apply(...args);
    });
    return clauses.filter(function(c) {
      return (c != null) && !empty(c);
    });
  };

  occurences = ["should", "must", "must_not", "filter"];

  module.exports = CompositeQuery = class CompositeQuery extends ConfigNode {
    apply(...args) {
      var body, clauseCount, clauses, j, key, len, occurence, ref, value;
      body = {};
      clauseCount = 0;
      ref = this._options;
      for (key in ref) {
        value = ref[key];
        if (indexOf.call(occurences, key) < 0) {
          body[key] = this._options[key];
        }
      }
      for (j = 0, len = occurences.length; j < len; j++) {
        occurence = occurences[j];
        clauses = collectClauses(occurence, this._options, args);
        clauseCount += clauses.length;
        if (clauses.length === 1) {
          body[occurence] = clauses[0];
        } else if (clauses.length > 1) {
          body[occurence] = clauses;
        }
      }
      if (clauseCount === 0) {
        return {
          match_all: {}
        };
      } else {
        return {
          bool: body
        };
      }
    }

  };

}).call(this);
