'use strict';

var count = require('ccount');

module.exports = enclose;

var re = /\s/;

/* Wrap `url` in angle brackets when needed, or when
 * forced.
 * In links, images, and definitions, the URL part needs
 * to be enclosed when it:
 *
 * - has a length of `0`;
 * - contains white-space;
 * - has more or less opening than closing parentheses.
 */
function enclose(uri, always) {
  if (always || uri.length === 0 || re.test(uri) || count(uri, '(') !== count(uri, ')')) {
    return '<' + uri + '>';
  }

  return uri;
}