class ApiLayoutItemTreeDataBuilder {
  constructor(startId = 10000) {
    this.idCounter = this.generateId(startId);
    this.nodeMap = new Map();
  }

  * generateId(start) {
    let id = start;
    while (true) {
      yield id++;
    }
  }

  cloneNode(node, parent) {

    // Create a shallow copy of the node, except for the children array
    let newNode = {
      ...node,
      id: this.idCounter.next().value, // Update with a new unique ID
      parent: parent ? parent.id : undefined // Set the new parent's ID if parent exists
    };

    // Remove children property to handle it separately
    delete newNode.children;
    this.nodeMap.set(newNode.id, newNode);
    return newNode;
  }

  replicateTree(node, parent = null) {
    const newNode = this.cloneNode(node, parent);
    newNode.children = []; // Initialize children array
    if (node.children && node.children.length > 0) {
      node.children.forEach(child => {
        const childCount = node.childOccCnt || 1;
        for (let i = 0; i < childCount; i++) {
          const childReplicas = this.replicateTree(child, newNode);
          newNode.children = newNode.children.concat(childReplicas);
        }
      });
    }

    return [newNode]; // Return an array containing only the new singular parent node with replicated children
  }

  createReplicatedTree(originalTree) {
    // console.log({originalTree});
    return this.replicateTree(originalTree)[0]; // Return the first element to maintain the tree structure
  }
}

export default ApiLayoutItemTreeDataBuilder;
