/*
 * Generated by PEG.js 0.10.0.
 *
 * http://pegjs.org/
 */

"use strict";

function peg$subclass(child, parent) {
  function ctor() { this.constructor = child; }
  ctor.prototype = parent.prototype;
  child.prototype = new ctor();
}

function peg$SyntaxError(message, expected, found, location) {
  this.message  = message;
  this.expected = expected;
  this.found    = found;
  this.location = location;
  this.name     = "SyntaxError";

  if (typeof Error.captureStackTrace === "function") {
    Error.captureStackTrace(this, peg$SyntaxError);
  }
}

peg$subclass(peg$SyntaxError, Error);

peg$SyntaxError.buildMessage = function(expected, found) {
  var DESCRIBE_EXPECTATION_FNS = {
        literal: function(expectation) {
          return "\"" + literalEscape(expectation.text) + "\"";
        },

        "class": function(expectation) {
          var escapedParts = "",
              i;

          for (i = 0; i < expectation.parts.length; i++) {
            escapedParts += expectation.parts[i] instanceof Array
              ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1])
              : classEscape(expectation.parts[i]);
          }

          return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]";
        },

        any: function(expectation) {
          return "any character";
        },

        end: function(expectation) {
          return "end of input";
        },

        other: function(expectation) {
          return expectation.description;
        }
      };

  function hex(ch) {
    return ch.charCodeAt(0).toString(16).toUpperCase();
  }

  function literalEscape(s) {
    return s
      .replace(/\\/g, '\\\\')
      .replace(/"/g,  '\\"')
      .replace(/\0/g, '\\0')
      .replace(/\t/g, '\\t')
      .replace(/\n/g, '\\n')
      .replace(/\r/g, '\\r')
      .replace(/[\x00-\x0F]/g,          function(ch) { return '\\x0' + hex(ch); })
      .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x'  + hex(ch); });
  }

  function classEscape(s) {
    return s
      .replace(/\\/g, '\\\\')
      .replace(/\]/g, '\\]')
      .replace(/\^/g, '\\^')
      .replace(/-/g,  '\\-')
      .replace(/\0/g, '\\0')
      .replace(/\t/g, '\\t')
      .replace(/\n/g, '\\n')
      .replace(/\r/g, '\\r')
      .replace(/[\x00-\x0F]/g,          function(ch) { return '\\x0' + hex(ch); })
      .replace(/[\x10-\x1F\x7F-\x9F]/g, function(ch) { return '\\x'  + hex(ch); });
  }

  function describeExpectation(expectation) {
    return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);
  }

  function describeExpected(expected) {
    var descriptions = new Array(expected.length),
        i, j;

    for (i = 0; i < expected.length; i++) {
      descriptions[i] = describeExpectation(expected[i]);
    }

    descriptions.sort();

    if (descriptions.length > 0) {
      for (i = 1, j = 1; i < descriptions.length; i++) {
        if (descriptions[i - 1] !== descriptions[i]) {
          descriptions[j] = descriptions[i];
          j++;
        }
      }
      descriptions.length = j;
    }

    switch (descriptions.length) {
      case 1:
        return descriptions[0];

      case 2:
        return descriptions[0] + " or " + descriptions[1];

      default:
        return descriptions.slice(0, -1).join(", ")
          + ", or "
          + descriptions[descriptions.length - 1];
    }
  }

  function describeFound(found) {
    return found ? "\"" + literalEscape(found) + "\"" : "end of input";
  }

  return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";
};

function peg$parse(input, options) {
  options = options !== void 0 ? options : {};

  var peg$FAILED = {},

      peg$startRuleIndices = { Expression: 0 },
      peg$startRuleIndex   = 0,

      peg$consts = [
        "||",
        peg$literalExpectation("||", false),
        function(head, tail) {
          		let s = [head];
                s = s.concat(tail.map(x=>x[1]));
                return new VersionSet(s);
            },
        peg$otherExpectation("Condition Items"),
        function(head, tail) {
          	let s = [head];
            s = s.concat(tail.map(x=> x[1]));
            return s;
          },
        function(head) {
          	return [head];
          },
        ">=",
        peg$literalExpectation(">=", false),
        function(v) {
              v.op = OP_GE;
              return v;
              },
        "<=",
        peg$literalExpectation("<=", false),
        function(v) {
             v.op = OP_LE; 
              return v;
              },
        "!=",
        peg$literalExpectation("!=", false),
        function(v) {
              v.op = OP_NOT;
              return v;
              },
        "!",
        peg$literalExpectation("!", false),
        "=",
        peg$literalExpectation("=", false),
        function(v) {
              v.op = OP_EQ;
              return v;
              },
        "<",
        peg$literalExpectation("<", false),
        function(v) {
              v.op = OP_LT;
              return v;
              },
        ">",
        peg$literalExpectation(">", false),
        function(v) {
              v.op = OP_GT;
              return v;
              },
        function(head) {
              head.op = OP_IS;
              return head;
              },
        peg$otherExpectation("version"),
        peg$otherExpectation("major.minor.patch"),
        ".",
        peg$literalExpectation(".", false),
        function(v, n) { v.patch = n; return v},
        peg$otherExpectation("major.minor"),
        function(v, n) {v.minor = n; return v},
        peg$otherExpectation("major"),
        function(n) {let v = new Version; v.major = n; return v},
        "*",
        peg$literalExpectation("*", false),
        "x",
        peg$literalExpectation("x", false),
        "X",
        peg$literalExpectation("X", false),
        function() {return '*';},
        peg$otherExpectation("integer"),
        /^[0-9]/,
        peg$classExpectation([["0", "9"]], false, false),
        function() { return parseInt(text(), 10); },
        peg$otherExpectation("whitespace"),
        /^[ \t\n\r]/,
        peg$classExpectation([" ", "\t", "\n", "\r"], false, false)
      ],

      peg$bytecode = [
        peg$decode("%;!/k#$%2 \"\"6 7!/,#;!/#$+\")(\"'#&'#0<*%2 \"\"6 7!/,#;!/#$+\")(\"'#&'#&/)$8\":\"\"\"! )(\"'#&'#"),
        peg$decode("<%;*/w#;\"/n$$%;)/,#;\"/#$+\")(\"'#&'#/9#06*%;)/,#;\"/#$+\")(\"'#&'#&&&#/2$;*/)$8$:$$\"\"!)($'#(#'#(\"'#&'#.D &%;*/:#;\"/1$;*/($8#:%#!!)(#'#(\"'#&'#=.\" 7#"),
        peg$decode("%2&\"\"6&7'/:#;*/1$;#/($8#:(#! )(#'#(\"'#&'#.\u013D &%2)\"\"6)7*/:#;*/1$;#/($8#:+#! )(#'#(\"'#&'#.\u0110 &%2,\"\"6,7-/:#;*/1$;#/($8#:.#! )(#'#(\"'#&'#.\xE3 &%2/\"\"6/70/:#;*/1$;#/($8#:.#! )(#'#(\"'#&'#.\xB6 &%21\"\"6172/:#;*/1$;#/($8#:3#! )(#'#(\"'#&'#.\x89 &%24\"\"6475/:#;*/1$;#/($8#:6#! )(#'#(\"'#&'#.\\ &%27\"\"6778/:#;*/1$;#/($8#:9#! )(#'#(\"'#&'#./ &%;#/' 8!::!! )"),
        peg$decode("<;$.) &;%.# &;&=.\" 7;"),
        peg$decode("<%;%/A#2=\"\"6=7>/2$;'/)$8#:?#\"\" )(#'#(\"'#&'#=.\" 7<"),
        peg$decode("<%;&/A#2=\"\"6=7>/2$;'/)$8#:A#\"\" )(#'#(\"'#&'#=.\" 7@"),
        peg$decode("<%;'/' 8!:C!! )=.\" 7B"),
        peg$decode("%2D\"\"6D7E.5 &2F\"\"6F7G.) &2H\"\"6H7I/& 8!:J! ).# &;("),
        peg$decode("<%$4L\"\"5!7M/,#0)*4L\"\"5!7M&&&#/& 8!:N! )=.\" 7K"),
        peg$decode("<$4P\"\"5!7Q/,#0)*4P\"\"5!7Q&&&#=.\" 7O"),
        peg$decode("<$4P\"\"5!7Q0)*4P\"\"5!7Q&=.\" 7O")
      ],

      peg$currPos          = 0,
      peg$savedPos         = 0,
      peg$posDetailsCache  = [{ line: 1, column: 1 }],
      peg$maxFailPos       = 0,
      peg$maxFailExpected  = [],
      peg$silentFails      = 0,

      peg$result;

  if ("startRule" in options) {
    if (!(options.startRule in peg$startRuleIndices)) {
      throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
    }

    peg$startRuleIndex = peg$startRuleIndices[options.startRule];
  }

  function text() {
    return input.substring(peg$savedPos, peg$currPos);
  }

  function location() {
    return peg$computeLocation(peg$savedPos, peg$currPos);
  }

  function expected(description, location) {
    location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)

    throw peg$buildStructuredError(
      [peg$otherExpectation(description)],
      input.substring(peg$savedPos, peg$currPos),
      location
    );
  }

  function error(message, location) {
    location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)

    throw peg$buildSimpleError(message, location);
  }

  function peg$literalExpectation(text, ignoreCase) {
    return { type: "literal", text: text, ignoreCase: ignoreCase };
  }

  function peg$classExpectation(parts, inverted, ignoreCase) {
    return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase };
  }

  function peg$anyExpectation() {
    return { type: "any" };
  }

  function peg$endExpectation() {
    return { type: "end" };
  }

  function peg$otherExpectation(description) {
    return { type: "other", description: description };
  }

  function peg$computePosDetails(pos) {
    var details = peg$posDetailsCache[pos], p;

    if (details) {
      return details;
    } else {
      p = pos - 1;
      while (!peg$posDetailsCache[p]) {
        p--;
      }

      details = peg$posDetailsCache[p];
      details = {
        line:   details.line,
        column: details.column
      };

      while (p < pos) {
        if (input.charCodeAt(p) === 10) {
          details.line++;
          details.column = 1;
        } else {
          details.column++;
        }

        p++;
      }

      peg$posDetailsCache[pos] = details;
      return details;
    }
  }

  function peg$computeLocation(startPos, endPos) {
    var startPosDetails = peg$computePosDetails(startPos),
        endPosDetails   = peg$computePosDetails(endPos);

    return {
      start: {
        offset: startPos,
        line:   startPosDetails.line,
        column: startPosDetails.column
      },
      end: {
        offset: endPos,
        line:   endPosDetails.line,
        column: endPosDetails.column
      }
    };
  }

  function peg$fail(expected) {
    if (peg$currPos < peg$maxFailPos) { return; }

    if (peg$currPos > peg$maxFailPos) {
      peg$maxFailPos = peg$currPos;
      peg$maxFailExpected = [];
    }

    peg$maxFailExpected.push(expected);
  }

  function peg$buildSimpleError(message, location) {
    return new peg$SyntaxError(message, null, null, location);
  }

  function peg$buildStructuredError(expected, found, location) {
    return new peg$SyntaxError(
      peg$SyntaxError.buildMessage(expected, found),
      expected,
      found,
      location
    );
  }

  function peg$decode(s) {
    var bc = new Array(s.length), i;

    for (i = 0; i < s.length; i++) {
      bc[i] = s.charCodeAt(i) - 32;
    }

    return bc;
  }

  function peg$parseRule(index) {
    var bc    = peg$bytecode[index],
        ip    = 0,
        ips   = [],
        end   = bc.length,
        ends  = [],
        stack = [],
        params, i;

    while (true) {
      while (ip < end) {
        switch (bc[ip]) {
          case 0:
            stack.push(peg$consts[bc[ip + 1]]);
            ip += 2;
            break;

          case 1:
            stack.push(void 0);
            ip++;
            break;

          case 2:
            stack.push(null);
            ip++;
            break;

          case 3:
            stack.push(peg$FAILED);
            ip++;
            break;

          case 4:
            stack.push([]);
            ip++;
            break;

          case 5:
            stack.push(peg$currPos);
            ip++;
            break;

          case 6:
            stack.pop();
            ip++;
            break;

          case 7:
            peg$currPos = stack.pop();
            ip++;
            break;

          case 8:
            stack.length -= bc[ip + 1];
            ip += 2;
            break;

          case 9:
            stack.splice(-2, 1);
            ip++;
            break;

          case 10:
            stack[stack.length - 2].push(stack.pop());
            ip++;
            break;

          case 11:
            stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));
            ip += 2;
            break;

          case 12:
            stack.push(input.substring(stack.pop(), peg$currPos));
            ip++;
            break;

          case 13:
            ends.push(end);
            ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);

            if (stack[stack.length - 1]) {
              end = ip + 3 + bc[ip + 1];
              ip += 3;
            } else {
              end = ip + 3 + bc[ip + 1] + bc[ip + 2];
              ip += 3 + bc[ip + 1];
            }

            break;

          case 14:
            ends.push(end);
            ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);

            if (stack[stack.length - 1] === peg$FAILED) {
              end = ip + 3 + bc[ip + 1];
              ip += 3;
            } else {
              end = ip + 3 + bc[ip + 1] + bc[ip + 2];
              ip += 3 + bc[ip + 1];
            }

            break;

          case 15:
            ends.push(end);
            ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);

            if (stack[stack.length - 1] !== peg$FAILED) {
              end = ip + 3 + bc[ip + 1];
              ip += 3;
            } else {
              end = ip + 3 + bc[ip + 1] + bc[ip + 2];
              ip += 3 + bc[ip + 1];
            }

            break;

          case 16:
            if (stack[stack.length - 1] !== peg$FAILED) {
              ends.push(end);
              ips.push(ip);

              end = ip + 2 + bc[ip + 1];
              ip += 2;
            } else {
              ip += 2 + bc[ip + 1];
            }

            break;

          case 17:
            ends.push(end);
            ips.push(ip + 3 + bc[ip + 1] + bc[ip + 2]);

            if (input.length > peg$currPos) {
              end = ip + 3 + bc[ip + 1];
              ip += 3;
            } else {
              end = ip + 3 + bc[ip + 1] + bc[ip + 2];
              ip += 3 + bc[ip + 1];
            }

            break;

          case 18:
            ends.push(end);
            ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);

            if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]) {
              end = ip + 4 + bc[ip + 2];
              ip += 4;
            } else {
              end = ip + 4 + bc[ip + 2] + bc[ip + 3];
              ip += 4 + bc[ip + 2];
            }

            break;

          case 19:
            ends.push(end);
            ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);

            if (input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]) {
              end = ip + 4 + bc[ip + 2];
              ip += 4;
            } else {
              end = ip + 4 + bc[ip + 2] + bc[ip + 3];
              ip += 4 + bc[ip + 2];
            }

            break;

          case 20:
            ends.push(end);
            ips.push(ip + 4 + bc[ip + 2] + bc[ip + 3]);

            if (peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))) {
              end = ip + 4 + bc[ip + 2];
              ip += 4;
            } else {
              end = ip + 4 + bc[ip + 2] + bc[ip + 3];
              ip += 4 + bc[ip + 2];
            }

            break;

          case 21:
            stack.push(input.substr(peg$currPos, bc[ip + 1]));
            peg$currPos += bc[ip + 1];
            ip += 2;
            break;

          case 22:
            stack.push(peg$consts[bc[ip + 1]]);
            peg$currPos += peg$consts[bc[ip + 1]].length;
            ip += 2;
            break;

          case 23:
            stack.push(peg$FAILED);
            if (peg$silentFails === 0) {
              peg$fail(peg$consts[bc[ip + 1]]);
            }
            ip += 2;
            break;

          case 24:
            peg$savedPos = stack[stack.length - 1 - bc[ip + 1]];
            ip += 2;
            break;

          case 25:
            peg$savedPos = peg$currPos;
            ip++;
            break;

          case 26:
            params = bc.slice(ip + 4, ip + 4 + bc[ip + 3]);
            for (i = 0; i < bc[ip + 3]; i++) {
              params[i] = stack[stack.length - 1 - params[i]];
            }

            stack.splice(
              stack.length - bc[ip + 2],
              bc[ip + 2],
              peg$consts[bc[ip + 1]].apply(null, params)
            );

            ip += 4 + bc[ip + 3];
            break;

          case 27:
            stack.push(peg$parseRule(bc[ip + 1]));
            ip += 2;
            break;

          case 28:
            peg$silentFails++;
            ip++;
            break;

          case 29:
            peg$silentFails--;
            ip++;
            break;

          default:
            throw new Error("Invalid opcode: " + bc[ip] + ".");
        }
      }

      if (ends.length > 0) {
        end = ends.pop();
        ip = ips.pop();
      } else {
        break;
      }
    }

    return stack[0];
  }



      const OP_EQ = "equal";
      const OP_IS = OP_EQ;
      const OP_GT = "greater";
      const OP_GE= "greaterequal";
      const OP_LT= "less";
      const OP_LE= "lessequal";
      const OP_NOT = "not";

      const VERBOSE = false;

      function Version(){
      	this.major = null;
          this.minor = null;
          this.patch = null;
          this.op = null;
      }

      const P = Version.prototype;

      P.toString = function() { 
          return `[${this.op ? this.op : "?"}]/v${this.major}.${this.minor}.${this.patch}`;
      }

      Object.defineProperty(Version.prototype, 'wildcard', {
          get: function() {
              return this.major === '*' || this.minor === '*' || this.patch === '*';
          }
      });
      Object.defineProperty(Version.prototype, 'anyMajor', {
          get: function() { return this.major === '*';}
      });
      Object.defineProperty(Version.prototype, 'anyMinor', {
          get: function() { return this.minor === '*';}
      });
      Object.defineProperty(Version.prototype, 'anyPatch', {
          get: function() { return this.patch === '*';}
      });
      P.toArray = function() {
          const r = [];
          if(this.major !== null) {
              r.push(this.major);
          }
          if(this.minor !== null) {
              r.push(this.minor);
          }
          if(this.patch !== null) {
              r.push(this.patch);
          }
          return r;
      };
      P.assertNotWildcard = function() {
          if(this.wildcard) {
              throw new Error("Source version should not be wildcard: "+this.toString());
          }
      }

      P.compareTo = function(o) {
          this.assertNotWildcard();
          if(o.wildcard) {
              throw new Error("Reference version should not be wildcard when comparing!");
          }
          const va = this.toArray();
          const vb = o.toArray();
          const l = Math.min(va.length, vb.length);
          let fillZeros = (a, l, ml) =>{ for(let i = l; i < ml; i++) a[i] = 0;}
          fillZeros(va, l, 3);
          fillZeros(vb, l, 3);
          let toFactor = (v) => {return (v[0] << 20) + (v[1] << 10) + (v[2]);}
          return toFactor(va) - toFactor(vb);
      };
      P.match = function(o) {
          if(VERBOSE) {
              console.log(`try match ${o}`);
          }
          this.assertNotWildcard();
          if(!o.wildcard) {
              throw new Error("Reference version should be wildcard when matching!");
          }

          if(VERBOSE) {
              console.log(` match major ${o.major}, any ${o.anyMajor}, ${this.major} <> ${o.major}`);
          }
          if(o.anyMajor) return true; 
          if(this.major !== o.major) return false;

          if(VERBOSE) {
              console.log(` match minor ${o.minor}, any ${o.anyMinor}, ${this.minor} <> ${o.minor}`);
          }
          if(o.anyMinor) return true;
          if(this.minor !== o.minor) return false;
          
          if(VERBOSE) {
              console.log(` match patch ${o.patch}, any ${o.anyPatch}`);
          }
          if(o.anyPatch) return true;
          return this.patch == o.patch;
      };

      P.test = function(o) {
          let op = o.op;
          if(op === OP_EQ) {
              return o.wildcard ? this.match(o) : this.compareTo(o) === 0;
          }
          if(op === OP_NOT) {
              return o.wildcard ? !this.match(o) : this.compareTo(o) !== 0;
          }
          if(o.wildcard){
              throw new Error("Can not compare to wildcard version");
          }
          const R = this.compareTo(o);
          if(op === OP_GE) {
              return R >= 0;
          }
          if(op === OP_LE) {
              return R <= 0;
          }
          if(op === OP_GT) {
              return R > 0;
          }
          if(op === OP_LT) {
              return R < 0;
          }
          throw new Error("invalidate operation " + op);
      };

      function VersionSet(data) {
          this.conds = data;
      }

      function allMatch(v, versions) {
          let t;
          let r = true;
          for(let c of versions) {
              t = v.test(c);
              if(VERBOSE) {
                  console.log(`test ${v} with ${c} => ${t}`);
              }
              if(!t){
                  r = false;
                  if(!VERBOSE) {
                      return false;
                  }
              }
          }
          return r;
      }

      function arrElmOr(arr, idx, dft){
          if(arr[idx] === undefined) return dft;
          return arr[idx];
      }

      VersionSet.prototype.match = function(o) {
          let ps = o.split('.');
          let v = new Version;
          v.major = parseInt(arrElmOr(ps, 0, 0), 10);
          v.minor = parseInt(arrElmOr(ps, 1, 0), 10);
          v.patch = parseInt(arrElmOr(ps, 2, 0), 10);
          if(VERBOSE) {
              console.log(`match version ${v}`);
          }
          for(let c of this.conds){
              if(allMatch(v, c)) {
                  return true;
              }            
          }
          return false;
      };


  peg$result = peg$parseRule(peg$startRuleIndex);

  if (peg$result !== peg$FAILED && peg$currPos === input.length) {
    return peg$result;
  } else {
    if (peg$result !== peg$FAILED && peg$currPos < input.length) {
      peg$fail(peg$endExpectation());
    }

    throw peg$buildStructuredError(
      peg$maxFailExpected,
      peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
      peg$maxFailPos < input.length
        ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)
        : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
    );
  }
}

module.exports = {
  SyntaxError: peg$SyntaxError,
  parse:       peg$parse
};
