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

@Injectable({
  providedIn: 'root'
})
export class XmlParserService {

  constructor() { }

  // Method to check for unclosed tags in an XML document
  findUnclosedTags(xmlString: string): string[] {
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(xmlString, 'application/xml');

    const unclosedTags: string[] = [];
    const stack: string[] = [];

    // Traverse all elements in the XML document
    const elements = xmlDoc.getElementsByTagName('*');
    for (let i = 0; i < elements.length; i++) {
      const element = elements[i];

      // If it's an opening tag, push to the stack
      if (element.tagName && !element.hasChildNodes()) {
        stack.push(element.tagName);
      }

      // If it's a closing tag, check if it matches the last element in the stack
      else if (element.tagName && stack.length > 0 && stack[stack.length - 1] !== element.tagName) {
        unclosedTags.push(stack[stack.length - 1]);
        stack.pop(); // Remove the mismatched tag from stack
      } else {
        stack.pop(); // Remove matched closing tag
      }
    }

    // If any opening tags are left in the stack, they are unclosed
    while (stack.length > 0) {
      unclosedTags.push(stack.pop());
    }

    return unclosedTags;
  }
}
