/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const isTraversable = (value) => {
  if (Array.isArray(value) && value.length) {
    return true;
  }
  if (typeof value !== 'object' || value === null) {
    return false;
  }
  if (Object.keys(value).length === 0) {
    return false;
  }
  return ![Function, String, Boolean, Number].some((c) => value instanceof c);
};

class Stack {
  constructor() {
    this.stack = [];
  }

  length() {
    return this.stack.length;
  }

  pop() {
    const { stack } = this;
    const { length } = stack;
    const last = stack[length - 1];

    0 < stack.length && (stack.length = stack.length - 1);
    return last;
  }

  push(item) {
    this.stack.push(item);
  }
}

class Path extends Stack {
  push(key, array) {
    if (this.array) {
      key = `[${key}]`;
    }
    this.array = array;

    super.push({
      key,
      array,
    });
  }
}

class Visitor {
  constructor(callback, maxDepth = Infinity) {
    this.callback = callback;
    this.maxDepth = maxDepth;
    this.paths = [];
    this.counter = new Stack();
    this.path = new Path();
    this.cache = new WeakSet();
  }

  visit(key, value, isMaxDepthReached) {
    if (isMaxDepthReached) {
      this.updateStacks(
        { counter: this.counter, path: this.path },
        null,
        null,
        isMaxDepthReached,
      );
      return;
    }
    // skip circular objects
    if (typeof value === 'object' && value !== null) {
      if (this.cache.has(value)) {
        // Circular reference found, discard key
        return;
      }
      // Store value in our collection
      this.cache.add(value);
    }

    let newVal;
    const depth = this.path.length();
    if (depth <= this.maxDepth) {
      newVal = this.callback(key, value, depth, this.path);
    }

    this.updateStacks({ counter: this.counter, path: this.path }, key, value);

    return newVal || value;
  }

  updateStacks(stacks, key, value, isMaxDepthReached) {
    if (isMaxDepthReached) {
      stacks.counter.pop();
      stacks.path.pop();
    }
    // We're decending into the object, so here we're
    // just building up the stacks.

    if (value && isTraversable(value)) {
      stacks.counter.push(Object.keys(value).length);
      stacks.path.push(key, Array.isArray(value));
      return;
    }

    // Otherwise we're decrementing / removing from stacks
    // when we process leaf nodes.
    // Look at the top value of stack
    const dec = stacks.counter.pop() - 1;
    // If non-zero we're still processessing at same level
    //  of depth, so leave the path stack alone.
    if (dec !== 0) {
      stacks.counter.push(dec);
      return;
    } else {
      // If it *is* zero, we need to remove the top item
      // from the stack, and maybe more (recursively).
      if (stacks.counter.length()) {
        stacks.path.pop();
        return this.updateStacks(
          { counter: this.counter, path: this.path },
          key,
          value,
        );
      }
      return;
    }
  }
}

function traverse(obj, fn, visitor, maxDepth) {
  if (typeof visitor === 'number') {
    maxDepth = visitor;
    visitor = undefined;
  }
  visitor =
    visitor ||
    new Visitor(function (key, value, depth, paths) {
      fn(key, value, depth, paths);
    }, maxDepth);

  traverseObject(obj, visitor, maxDepth);
}

function traverseObject(obj, visitor, remainingDepth = 250, visited = new Set()) {
  if (!obj || visited.has(obj)) {
    return;
  }

  if (visitor.path.length() < 1) {
    visitor.visit('', obj);
    visited.add(obj);
  }

  // This is done just to reset the stack, without changing the current impletion
  if (remainingDepth == 0) {
    visitor.visit(null, null, true);
    visited.add(obj);
    return;
  }

  Object.entries(obj).forEach(([key, value]) => {
    visitor.visit(key, value);
    visited.add(obj);
    if (value && typeof value === 'object') {
      traverseObject(value, visitor, remainingDepth - 1, visited);
    }
  });
}

module.exports.Visitor = Visitor;
module.exports.traverse = traverse;
