using System;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Inventory.Interfaces;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Util;

namespace ReallifeGamemode.Server.Inventory.Items
{
  public abstract class ConsumableItem : IUsableItem
  {
    public abstract int HpAmount { get; }
    public abstract int Id { get; }
    public abstract string Name { get; }
    public abstract string Description { get; }
    public abstract int Gewicht { get; }
    public abstract string Einheit { get; }
    public abstract uint Object { get; }
    public abstract int Price { get; }
    public abstract float Cooldown { get; }

    public abstract void Consume(UserItem uItem);

    public bool Use(UserItem uItem)
    {
      User user = uItem.GetUser();
      if (user.Player == null || !user.Player.IsLoggedIn())
        return false;

      if (!HasCooldownElapsed(user))
      {
        DateTime time = InventoryManager.itemCooldown[user.Id];
        int timeUntillNextUse = (int)(time - DateTime.Now).TotalSeconds;
        uItem.GetUser().Player.TriggerEvent("Error", $"Versuche es nach {timeUntillNextUse} Sekunden erneut.");
        return false;
      }

      DateTime cooldown = DateTime.Now.AddMilliseconds(Cooldown);
      InventoryManager.itemCooldown.Add(user.Id, cooldown);

      Consume(uItem);
      return true;
    }

    private bool HasCooldownElapsed(User user)
    {
      if (user.Player == null || !user.Player.IsLoggedIn())
        return false;

      if (!InventoryManager.itemCooldown.ContainsKey(user.Id))
        return true;

      int timeRemaining = (int)(InventoryManager.itemCooldown[user.Id] - DateTime.Now).TotalSeconds;

      if (timeRemaining <= 0)
        InventoryManager.itemCooldown.Remove(user.Id);

      return timeRemaining <= 0;
    }
  }
}
