import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class XPathService {
  getXPath(node: Node): string {
    if (!node || node.nodeType !== 1) return '';

    // Construct the XPath step-by-step
    let path = '';
    while (node) {
      let index = 1;
      let sibling = node.previousSibling;

      // Calculate the index of the current node among its siblings with the same tag
      while (sibling) {
        if (sibling.nodeType === 1 && sibling.nodeName === node.nodeName) {
          index++;
        }
        sibling = sibling.previousSibling;
      }

      // Build the path for the current node
      const nodeName = node.nodeName;
      path = `/${nodeName}[${index}]${path}`;

      // Move to the parent node
      node = node.parentNode as Node;
    }

    return path;
  }
}
