// Generated by CoffeeScript 2.5.1
(function() {
  var AND, DEFAULT, DQUOT, MUST, MUST_NOT, NOT, OR, QLF, SEQ, SHOULD, SQUOT, TERM, escapeDQ, escapeSQ, isTerm, par, priorities, unparse;

  ({isTerm, TERM, MUST, MUST_NOT, SHOULD, QLF, SEQ, OR, AND, NOT, DQUOT, SQUOT} = require("./ast-helper"));

  DEFAULT = "DEFAULT";

  priorities = {
    TERM: 0,
    DQUOT: 0,
    SQUOT: 0,
    QLF: 1,
    MUST: 2,
    MUST_NOT: 2,
    SHOULD: 2,
    DEFAULT: 2,
    NOT: 3,
    AND: 4,
    SEQ: 5,
    OR: 6
  };

  escapeDQ = function(s) {
    return s.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
  };

  escapeSQ = function(s) {
    return s.replace(/\\/g, '\\\\').replace(/'/g, '\\\'');
  };

  par = function(op, term) {
    var child, head, parent;
    // poor man's function currying...
    if (term == null) {
      return function(t) {
        return par(op, t);
      };
    } else if (isTerm(term)) {
      [head] = term;
      parent = priorities[op];
      child = priorities[head];
      if ((parent == null) || (child == null) || parent <= child) {
        return "(" + unparse(term) + ")";
      } else {
        return unparse(term);
      }
    } else {
      return term;
    }
  };

  unparse = function(ast) {
    var args, first, head, second;
    if (!isTerm(ast)) {
      return ast;
    }
    [head, ...args] = ast;
    [first, second] = args;
    switch (head) {
      case TERM:
        return first;
      case MUST:
        return "+" + par(MUST, first);
      case MUST_NOT:
        return "-" + par(MUST_NOT, first);
      case SHOULD:
        return "?" + par(SHOULD, first);
      case QLF:
        return `${first}:${par(QLF, second)}`;
      case SEQ:
        return args.map(par(SEQ)).join(" ");
      case OR:
        return args.map(par(OR)).join(" OR ");
      case AND:
        return args.map(par(AND)).join(" AND ");
      case NOT:
        return "NOT " + par(NOT, first);
      case DQUOT:
        return "\"" + escapeDQ(first) + "\"";
      case SQUOT:
        return "'" + escapeSQ(first) + "'";
      case DEFAULT:
        return "!" + par(DEFAULT, first);
      default:
        throw new Error(`cannot unparse op ${head}`);
    }
  };

  module.exports = unparse;

}).call(this);
