import { Component, OnInit, ViewChild } from '@angular/core';
import { MatchService } from '../match.service'
import { Match, PatternResult, MatchedResult} from '../matched-result.model'
import { AceEditorDirective } from '../ace-editor.directive';

@Component({
  selector: 'app-matchresult',
  templateUrl: './matchresult.component.html',
  styleUrls: ['./matchresult.component.css']
})
export class MatchresultComponent implements OnInit {
  @ViewChild(AceEditorDirective,  { static: false }) aceEditorDirective!: AceEditorDirective;
  matches: Match[] = [];
  matchedResults: MatchedResult[] = []; // Store matched results
  loadingIndex: number | null = null;
  xmlContent = '';
  constructor(private matchService: MatchService) { }

  ngOnInit() {
    this.matchService.matches$.subscribe(matches => {
      this.matchedResults = matches;       
    });
  }

  loadFileContent(index: number): void {
    this.loadingIndex = index;
   // this.aceEditorDirective.appAceEditor = "";

    setTimeout(() => {
      
      const matchedResult = this.matchedResults[index];
      this.xmlContent = matchedResult.content;

      if(this.aceEditorDirective){
        this.aceEditorDirective.updateEditorContent(this.xmlContent);
     }    

      
    
     // Load the file content into the ACE editor
      //this.aceEditorDirective.appAceEditor = this.xmlContent;
    
     // Highlight the patterns
      this.highlightPattern(matchedResult.patternResults);
      // Your existing logic to load the file content
      console.log('Loading file content for:', this.matchedResults[index].fileName);
  
      // Reset the loading state after content is loaded
      this.loadingIndex = null;
    }, 1000);

  
  }  
  
  highlightPattern(patternResults: PatternResult[]) {
      // Clear previous highlights before adding new ones

      if(this.aceEditorDirective){
    this.aceEditorDirective.clearMarkers(); 
    this.aceEditorDirective.highlightMatch(patternResults);
      }
  }

}
