var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var match = String.prototype.match;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;

function lowbyte(c) {
  var n = c.charCodeAt(0);
  var x = {
    8: 'b',
    9: 't',
    10: 'n',
    12: 'f',
    13: 'r'
  }[n];
  if (x) {
    return '\\' + x;
  }
  return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}

function toStr(obj) {
  return objectToString.call(obj);
}

function isSymbol(obj) {
  return toStr(obj) === '[object Symbol]';
}

function isArray(obj) {
  return toStr(obj) === '[object Array]';
}

function isDate(obj) {
  return toStr(obj) === '[object Date]';
}

function isRegExp(obj) {
  return toStr(obj) === '[object RegExp]';
}

function isError(obj) {
  return toStr(obj) === '[object Error]';
}

function isString(obj) {
  return toStr(obj) === '[object String]';
}

function isNumber(obj) {
  return toStr(obj) === '[object Number]';
}

function isBigInt(obj) {
  return toStr(obj) === '[object BigInt]';
}

function isBoolean(obj) {
  return toStr(obj) === '[object Boolean]';
}

function isMap(x) {
  if (!mapSize || !x || typeof x !== 'object') {
    return false;
  }
  try {
    mapSize.call(x);
    try {
      setSize.call(x);
    } catch (s) {
      return true;
    }
    return x instanceof Map; // core-js workaround, pre-v2.5.0
  } catch (e) {}
  return false;
}

function isWeakMap(x) {
  if (!weakMapHas || !x || typeof x !== 'object') {
    return false;
  }
  try {
    weakMapHas.call(x, weakMapHas);
    try {
      weakSetHas.call(x, weakSetHas);
    } catch (s) {
      return true;
    }
    return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
  } catch (e) {}
  return false;
}

function isSet(x) {
  if (!setSize || !x || typeof x !== 'object') {
    return false;
  }
  try {
    setSize.call(x);
    try {
      mapSize.call(x);
    } catch (m) {
      return true;
    }
    return x instanceof Set; // core-js workaround, pre-v2.5.0
  } catch (e) {}
  return false;
}

function isWeakSet(x) {
  if (!weakSetHas || !x || typeof x !== 'object') {
    return false;
  }
  try {
    weakSetHas.call(x, weakSetHas);
    try {
      weakMapHas.call(x, weakMapHas);
    } catch (s) {
      return true;
    }
    return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
  } catch (e) {}
  return false;
}

function isElement(x) {
  if (!x || typeof x !== 'object') {
    return false;
  }
  if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
    return true;
  }
  return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}

function wrapQuotes(s, defaultStyle, opts) {
  var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
  return quoteChar + s + quoteChar;
}

function quote(s) {
  return String(s).replace(/"/g, '&quot;');
}

var hasOwn = Object.prototype.hasOwnProperty || function (key) {
  return key in this;
};

function has(obj, key) {
  return hasOwn.call(obj, key);
}

function nameOf(f) {
  if (f.name) {
    return f.name;
  }
  var m = match.call(f, /^function\s*([\w$]+)/);
  if (m) {
    return m[1];
  }
  return null;
}

function indexOf(xs, x) {
  if (xs.indexOf) {
    return xs.indexOf(x);
  }
  for (var i = 0, l = xs.length; i < l; i++) {
    if (xs[i] === x) {
      return i;
    }
  }
  return -1;
}

function inspectString(str, opts) {
  // eslint-disable-next-line no-control-regex
  var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
  return wrapQuotes(s, 'single', opts);
}

function getSpace(indentation) {
  if (!indentation) {
    return '';
  }

  let spaces = '';
  for (let i = 0; i < indentation; i++) {
    spaces += ' ';
  }
  return spaces;
}

function getArrayIndentation(indentation, inNewLine) {
  if (!inNewLine) {
    return {
      children: 1,
      end: 0,
      start: 0
    };
  }

  return {
    children: indentation + 2,
    end: indentation,
    start: indentation + 2
  };
}

function markBoxed(str) {
  return `"Object(${str})"`;
}

function weakCollectionOf(type) {
  return `"${type} {?}"`;
}

function collectionOf(type, size, entries) {
  return `"${type}(${size}) [${entries.join(', ')}]"`;
}

function arrObjKeys(obj, inspect, indentation, inNewLine) {
  var isArr = isArray(obj);
  var xs = [];

  if (isArr) {
    xs.length = obj.length;
    for (var i = 0; i < obj.length; i++) {
      xs[i] = has(obj, i) ? inspect(obj[i], obj, undefined, indentation, inNewLine) : '"<empty item>"';
    }
  }

  for (var key in obj) { // eslint-disable-line no-restricted-syntax
    if (!has(obj, key)) {
      continue; // eslint-disable-line no-restricted-syntax, no-continue
    }

    if (isArr && String(Number(key)) === key && key < obj.length) {
      continue; // eslint-disable-line no-restricted-syntax, no-continue
    }

    if ((/[^\w$]/).test(key)) {
      xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj, undefined, indentation, inNewLine));
    } else {
      xs.push('"' + key + '": ' + inspect(obj[key], obj, undefined, indentation, inNewLine));
    }
  }

  return xs;
}

module.exports = function inspect_(obj, options, depth, seen, indentation, inNewLine) {
  var opts = options || {};
  indentation = indentation || 0;
  inNewLine = inNewLine === undefined ? true : inNewLine;
  var newLine = inNewLine ? '\n' : '';

  if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
    throw new TypeError('option "quoteStyle" must be "single" or "double"');
  }

  function inspect(value, from, options, indentation, inNewLine) {
    if (from) {
      seen = seen.slice();
      seen.push(from);
    }

    return inspect_(value, options || opts, depth + 1, seen, indentation, inNewLine);
  }

  if (typeof obj === 'undefined') {
    return '"undefined"';
  }

  if (obj === null) {
    return 'null';
  }

  if (typeof obj === 'boolean') {
    return obj ? 'true' : 'false';
  }

  if (typeof obj === 'string') {
    return opts.noWrap ? inspectString(obj, opts) : `"${inspectString(obj, opts)}"`;
  }

  if (typeof obj === 'number') {
    if (obj === 0) {
      return Infinity / obj > 0 ? '0' : '-0';
    }
    return String(obj);
  }

  if (typeof obj === 'bigint') {
    return opts.noWrap ? String(obj) : `"${String(obj)}n"`
  }

  var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
  if (typeof depth === 'undefined') {
    depth = 0;
  }

  if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
    return opts.noWrap ? '[Object]' : '"[Object]"';
  }

  if (typeof seen === 'undefined') {
    seen = [];
  } else if (indexOf(seen, obj) >= 0) {
    return opts.noWrap ? '[Circular]' : '"[Circular]"';
  }

  if (typeof obj === 'function') {
    var name = nameOf(obj);
    return '"[Function' + (name ? ': ' + name : '') + ']"';
  }

  if (isSymbol(obj)) {
    var symString = Symbol.prototype.toString.call(obj);
    return typeof obj === 'object' ? markBoxed(symString) : `"${symString}"`;
  }

  if (isElement(obj)) {
    var s = '<' + String(obj.nodeName).toLowerCase();
    var attrs = obj.attributes || [];
    for (var i = 0; i < attrs.length; i++) {
      s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
    }
    s += '>';
    if (obj.childNodes && obj.childNodes.length) {
      s += '...';
    }
    s += '</' + String(obj.nodeName).toLowerCase() + '>';
    return opts.noWrap ? s : `"${s}"`;
  }

  if (isArray(obj)) {
    if (obj.length === 0) {
      return '[]';
    }

    const { children, end, start } = getArrayIndentation(indentation, inNewLine);
    const val = arrObjKeys(obj, inspect, children || indentation, inNewLine).join(',' + newLine + getSpace(children));
    return '[' + newLine + getSpace(start) + val + newLine + getSpace(end) + ']';
  }

  if (isError(obj)) {
    const { children, end, start } = getArrayIndentation(indentation, inNewLine);
    var parts = arrObjKeys(obj, inspect, children, inNewLine);
    if (parts.length === 0) {
      return '"Error [' + String(obj) + ']"';
    }
    const val = parts.join(',' + newLine + getSpace(children));
    return '"Error [' + String(obj) + ']"' + '{' + newLine + getSpace(start) + val + newLine + getSpace(end) + '}';
  }

  if (isMap(obj)) {
    var mapParts = [];
    const options = { quoteStyle: 'single', noWrap: true };

    mapForEach.call(obj, function (value, key) {
      mapParts.push(
        inspect(key, obj, options, indentation, newLine) + ' => ' + inspect(value, obj, options, indentation, newLine)
      );
    });

    return collectionOf('Map', mapSize.call(obj), mapParts);
  }

  if (isSet(obj)) {
    var setParts = [];
    setForEach.call(obj, function (value) {
      setParts.push(inspect(value, obj, undefined, indentation, newLine));
    });

    return collectionOf('Set', setSize.call(obj), setParts);
  }

  if (isWeakMap(obj)) {
    return weakCollectionOf('WeakMap');
  }

  if (isWeakSet(obj)) {
    return weakCollectionOf('WeakSet');
  }

  if (isNumber(obj)) {
    return markBoxed(inspect(Number(obj), undefined, undefined, 0, false));
  }

  if (isBigInt(obj)) {
    return markBoxed(inspect(bigIntValueOf.call(obj), undefined, undefined, 0, false));
  }

  if (isBoolean(obj)) {
    return markBoxed(booleanValueOf.call(obj));
  }

  if (isString(obj)) {
    return markBoxed(inspect(String(obj), undefined, undefined, 0, false));
  }

  if (isRegExp(obj)) {
    return `"RegExp ${String(obj)}"`;
  }

  if (Buffer.isBuffer(obj)) {
    return `"${obj.inspect()}"`;
  }

  if (!isDate(obj)) {
    const { children, end, start } = getArrayIndentation(indentation, inNewLine);
    var xs = arrObjKeys(obj, inspect, children || indentation, newLine);
    if (xs.length === 0) {
      return '{}';
    }
    const value = xs.join(',' + newLine + getSpace(children));
    return '{' + newLine + getSpace(start) + value + newLine + getSpace(end) + '}';
  }

  return opts.noWrap ? String(obj) : `"'${String(obj)}'"`;
};
