LinkFormatter.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using Server.MirEnvir;
  6. namespace Server.MirObjects
  7. {
  8. public static class LinkFormatter
  9. {
  10. private static readonly Regex LinkRegex = new Regex(@"\<\$(?<type>MONSTER|NPC|ITEM):(?<idx>\d+)\>", RegexOptions.IgnoreCase | RegexOptions.Compiled);
  11. public static string ReplacePlaceholders(string input, Action<string, int> linkRequested = null)
  12. {
  13. if (string.IsNullOrEmpty(input)) return input;
  14. if (!input.Contains("<$")) return input;
  15. return LinkRegex.Replace(input, match =>
  16. {
  17. string type = match.Groups["type"].Value.ToUpper();
  18. if (!int.TryParse(match.Groups["idx"].Value, out int index))
  19. return match.Value;
  20. linkRequested?.Invoke(type, index);
  21. string displayName = GetDisplayName(type, index);
  22. if (string.IsNullOrEmpty(displayName))
  23. return $"[{type}:{index}]";
  24. return $"[{type}:{index}|{displayName}]";
  25. });
  26. }
  27. public static List<string> ReplacePlaceholders(IEnumerable<string> source, Action<string, int> linkRequested = null)
  28. {
  29. if (source == null) return null;
  30. return source.Select(line => ReplacePlaceholders(line, linkRequested)).ToList();
  31. }
  32. private static string GetDisplayName(string type, int index)
  33. {
  34. switch (type)
  35. {
  36. case "MONSTER":
  37. return Envir.Main.GetMonsterInfo(index)?.Name;
  38. case "NPC":
  39. return Envir.Main.GetNPCInfo(index)?.Name;
  40. case "ITEM":
  41. return Envir.Main.GetItemInfo(index)?.Name;
  42. default:
  43. return null;
  44. }
  45. }
  46. }
  47. }