using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GTANetworkAPI;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Types;

namespace ReallifeGamemode.Server.Admin
{
  public class AntiCheat : Script
  {
    private static TimeSpan antiCheatMessageCooldown = new TimeSpan(0, 0, 30);
    private static Dictionary<(string, string), DateTime> lastAntiCheatBroadcastTime = new Dictionary<(string, string), DateTime>();

    [ServerEvent(Event.PlayerWeaponSwitch)]
    public void OnAntiCheatPlayerWeeaponSwitch(Player player, WeaponHash oldWeapon, WeaponHash newWeapon)
    {
      player.TriggerEvent("SERVER:AntiCheat:weaponSwap");
    }

    [RemoteEvent("CLIENT:CheatDetection")]
    public void OnAntiCheatCheatDetected(Player cheater, string cheat)
    {
      if (!cheater.IsLoggedIn())
      {
        return;
      }

      if(cheater.IsAdminDuty())
      {
        return;
      }

      if (lastAntiCheatBroadcastTime.Any(a => a.Key.Item1 == cheater.Name && a.Key.Item2 == cheat)
        && DateTime.Now - lastAntiCheatBroadcastTime[(cheater.Name, cheat)] < antiCheatMessageCooldown)
      {
        return;
      }
      lastAntiCheatBroadcastTime[(cheater.Name, cheat)] = DateTime.Now;
      ChatService.BroadcastAdmin($"~r~[ANTICHEAT]~s~ Verdacht auf ~y~{cheat}~s~ bei ~y~{cheater.Name}~s~ (~y~{cheater.Handle.Value}~s~)", AdminLevel.ADMIN);
    }

    internal static void NoTpAntiCheatForPlayer(string name)
    {
      lastAntiCheatBroadcastTime[(name, "Flyhack/Teleport")] = DateTime.Now.Subtract(antiCheatMessageCooldown).Add(TimeSpan.FromSeconds(5));
    }

    internal static void NoHealthAntiCheatForPlayer(string name)
    {
      lastAntiCheatBroadcastTime[(name, "Healkey (unexpected HP added)")] = DateTime.Now.Subtract(antiCheatMessageCooldown).Add(TimeSpan.FromSeconds(5));
    }
  }
}
