import { Injectable, inject } from '@angular/core';
import { JournalEntry, Npcs, Npc } from 'src/interfaces/interfaces';
import { DataService } from 'src/services/data/data.service';

@Injectable({
  providedIn: 'root',
})
export class TooltipService {
  private dataService: DataService = inject(DataService);

  public tooltipifyEntry(entry: string): any {
    const content = this.replaceNpcs(entry);
    const matches = entry.match(/(?<=@)\w+/g);
    const uniqueMatches = [...new Set(matches)];
    // get the descriptions from the data service
    const npcs = this.dataService.npcs;
    const npcArray = Object.keys(npcs)
      .map((key) => npcs[key])
      .flat();
    let npcsDescription: any = {};

    uniqueMatches.forEach((name) => {
      const npc = npcArray.find(
        (npc: Npc) => npc.name === name || npc.identifier === name,
      );
      if (npc) {
        // Add it to the npcDescription object
        npcsDescription[name] = npc.shortDescription;
      } else {
        // Add a placeholder to the npcDescription object
        npcsDescription[name] = 'Keine Person mit diesem Name gefunden.';
      }
    });

    return {
      content: content,
      npcs: uniqueMatches,
      npcDescriptions: npcsDescription,
    };
  }

  private replaceNpcs(content: string): string {
    return content.replace(/@(\w+)/g, "<span class='$1'></span>");
  }
}
