// Generated by CoffeeScript 1.6.2
/*
Copyright (c) 2012 Niclas Hoyer, Fiona Schmidtke, Ben Blank
Copyright (c) 2014 Niclas Hoyer, Pavel Strashkin

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

var getBestLanguageMatch, getBestMatch, getBestMediaMatch, middleware, parseAccept, parseHeaderField, parseMediaType, parseParams, parseStandard, sortMediaType, sortQuality, trimsplit,
  __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; };

trimsplit = function(str, delimiter) {
  var strs, _i, _len, _results;

  strs = str.split(delimiter);
  _results = [];
  for (_i = 0, _len = strs.length; _i < _len; _i++) {
    str = strs[_i];
    _results.push(str.trim());
  }
  return _results;
};

parseParams = function(str) {
  var param, paramToObj, params, paramstrs, q, strs, _i, _len;

  paramToObj = function(str, obj) {
    var param;

    param = trimsplit(str, '=');
    return obj[param[0]] = param[1];
  };
  strs = trimsplit(str, ';');
  paramstrs = strs.slice(1);
  params = {};
  for (_i = 0, _len = paramstrs.length; _i < _len; _i++) {
    param = paramstrs[_i];
    paramToObj(param, params);
  }
  if (params.q != null) {
    q = Number(params.q);
  } else {
    q = 1;
  }
  return {
    value: strs[0],
    params: params,
    quality: q
  };
};

parseMediaType = function(obj) {
  var mediarange;

  mediarange = trimsplit(obj.value, '/');
  return {
    type: mediarange[0],
    subtype: mediarange[1],
    params: obj.params,
    mediarange: obj.value,
    quality: obj.quality
  };
};

parseStandard = function(obj) {
  return obj.value;
};

parseHeaderField = function(str, map, sort, match) {
  var obj, objects, strs;

  if (str == null) {
    return;
  }
  strs = trimsplit(str, ',');
  objects = (function() {
    var _i, _len, _results;

    _results = [];
    for (_i = 0, _len = strs.length; _i < _len; _i++) {
      str = strs[_i];
      _results.push(parseParams(str));
    }
    return _results;
  })();
  map = map != null ? map : parseStandard;
  sort = sort != null ? sort : sortQuality;
  objects = (function() {
    var _i, _len, _results;

    _results = [];
    for (_i = 0, _len = objects.length; _i < _len; _i++) {
      obj = objects[_i];
      _results.push(map(obj));
    }
    return _results;
  })();
  objects.sort(sort);
  return Object.defineProperty(objects, 'getBestMatch', {
    value: match != null ? match : getBestMatch
  });
};

parseAccept = function(str) {
  str = str != null ? str : '*/*';
  return parseHeaderField(str, parseMediaType, sortMediaType, getBestMediaMatch);
};

sortQuality = function(a, b) {
  if (a.quality < b.quality) {
    return 1;
  }
  if (a.quality > b.quality) {
    return -1;
  }
};

sortMediaType = function(a, b) {
  if (a.quality < b.quality) {
    return 1;
  }
  if (a.quality > b.quality) {
    return -1;
  }
  if (a.type === '*' && b.type !== '*') {
    return 1;
  }
  if (a.type !== '*' && b.type === '*') {
    return -1;
  }
  if (a.subtype === '*' && b.subtype !== '*') {
    return 1;
  }
  if (a.subtype !== '*' && b.subtype === '*') {
    return -1;
  }
  if (Object.keys(a.params).length < Object.keys(b.params).length) {
    return 1;
  }
  if (Object.keys(a.params).length > Object.keys(b.params).length) {
    return -1;
  }
  return 0;
};

getBestMatch = function(candidates) {
  var acceptable, accepted, _ref;

  acceptable = (function() {
    var _i, _len, _results;

    _results = [];
    for (_i = 0, _len = this.length; _i < _len; _i++) {
      accepted = this[_i];
      if (__indexOf.call(candidates, accepted) >= 0) {
        _results.push(accepted);
      }
    }
    return _results;
  }).call(this);
  return (_ref = acceptable[0]) != null ? _ref : (__indexOf.call(this, "*") >= 0 ? candidates[0] : void 0);
};

getBestLanguageMatch = function(candidates) {
  var acceptable, accepted, candidate, i, length, value, _i, _j, _len, _len1;

  acceptable = (function() {
    var _i, _len, _results;

    _results = [];
    for (_i = 0, _len = candidates.length; _i < _len; _i++) {
      candidate = candidates[_i];
      _results.push({
        value: candidate,
        q: -1,
        length: 0
      });
    }
    return _results;
  })();
  for (_i = 0, _len = acceptable.length; _i < _len; _i++) {
    candidate = acceptable[_i];
    value = candidate.value + "-";
    for (i = _j = 0, _len1 = this.length; _j < _len1; i = ++_j) {
      accepted = this[i];
      if ((value.indexOf(accepted + "-")) === 0) {
        length = (accepted.split("-")).length;
        if (length > candidate.length) {
          candidate.q = i;
          candidate.length = length;
        }
      }
    }
  }
  acceptable.sort(function(a, b) {
    if (a.q === -1 && b.q !== -1) {
      return 1;
    }
    if (a.q !== -1 && b.q === -1) {
      return -1;
    }
    if (a.q > b.q) {
      return 1;
    }
    if (a.q < b.q) {
      return -1;
    }
    if (a.length < b.length) {
      return 1;
    }
    if (a.length > b.length) {
      return -1;
    }
    return 0;
  });
  if (acceptable[0].q !== -1) {
    return acceptable[0].value;
  } else {
    if (__indexOf.call(this, "*") >= 0) {
      return candidates[0];
    }
  }
};

getBestMediaMatch = function(candidates) {
  var acceptable, accepted, candidate, i, param, prec, value, _i, _j, _len, _len1, _ref;

  acceptable = (function() {
    var _i, _len, _results;

    _results = [];
    for (_i = 0, _len = candidates.length; _i < _len; _i++) {
      candidate = candidates[_i];
      _results.push(parseMediaType(parseParams(candidate)));
    }
    return _results;
  })();
  for (i = _i = 0, _len = acceptable.length; _i < _len; i = ++_i) {
    candidate = acceptable[i];
    candidate.index = i;
    candidate.quality = 0;
    candidate.prec = -1;
    for (_j = 0, _len1 = this.length; _j < _len1; _j++) {
      accepted = this[_j];
      prec = -1;
      if (accepted.type === candidate.type) {
        if (accepted.subtype === candidate.subtype) {
          prec = 2;
          _ref = accepted.params;
          for (param in _ref) {
            value = _ref[param];
            if (param !== "q") {
              if (candidate.params[param] === value) {
                prec++;
              }
            }
          }
        } else if (accepted.subtype === "*") {
          prec = 1;
        }
      } else if (accepted.type === "*" && accepted.subtype === "*") {
        prec = 0;
      }
      if (prec > candidate.prec) {
        candidate.prec = prec;
        candidate.quality = accepted.quality;
      }
    }
  }
  acceptable.sort(function(a, b) {
    if (a.quality < b.quality) {
      return 1;
    }
    if (a.quality > b.quality) {
      return -1;
    }
    if (a.prec < b.prec) {
      return 1;
    }
    if (a.prec > b.prec) {
      return 1;
    }
    if (a.index < b.index) {
      return -1;
    }
    if (a.index > b.index) {
      return 1;
    }
  });
  if (acceptable[0].quality) {
    return candidates[acceptable[0].index];
  }
};

middleware = function(req, res, next) {
  req.accept = {
    types: parseAccept(req.headers.accept),
    charsets: parseHeaderField(req.headers['accept-charset']),
    encodings: parseHeaderField(req.headers['accept-encoding']),
    languages: parseHeaderField(req.headers['accept-language'], null, null, getBestLanguageMatch),
    ranges: parseHeaderField(req.headers['accept-ranges'])
  };
  return next();
};

module.exports = middleware;

module.exports.parser = parseHeaderField;
