using System.Text.RegularExpressions;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities.Logs.Chat;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Services;

namespace ReallifeGamemode.Server.Events
{
  public class Chat : Script
  {
    [ServerEvent(Event.ChatMessage)]
    public void ChatEvent(Player player, string message)
    {
      if(!player.IsLoggedIn())
      {
        return;
      }

      string serverMsg = Regex.Replace(message, "(~[a-zA-Z]~)|(!{(.*)})", "");
      if (serverMsg.Trim().Length == 0) return;

      using var dbContext = new DatabaseContext();

      var logEntry = new LocalChatLogEntry()
      {
        Text = serverMsg,
        UserId = player.GetUser(dbContext).Id
      };

      dbContext.LocalChatLogs.Add(logEntry);
      dbContext.SaveChanges();

      NAPI.Player.GetPlayersInRadiusOfPlayer(25, player).ForEach(p =>
      {
        ChatService.SendMessage(p, $"{player.Name} sagt: {serverMsg}");
      });
    }
  }
}
