using System;
using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Server.Core.API;
using ReallifeGamemode.Server.Core.API.API;

namespace ReallifeGamemode.Server.Core.RageMP
{
  public class RageAPI : IAPI
  {
    public IColShapeAPI ColShape => new RageColShapeAPI();

    public IVehicleAPI Vehicle => new RageVehicleAPI();

    public IMarkerAPI Marker => new RageMarkerAPI();

    public ITextLabelAPI TextLabel => new RageTextLabelAPI();

    public IBlipAPI Blip => new RageBlipAPI();

    public void DisableDefaultCommandErrorMessages()
    {
      NAPI.Server.SetCommandErrorMessage(string.Empty);
      //NAPI.Server.SetGlobalDefaultCommandMessages(false);
    }

    public void SetGlobalChatEnabled(bool enable)
    {
      NAPI.Server.SetGlobalServerChat(enable);
    }

    public void DisableDefaultSpawnBehavior()
    {
      NAPI.Server.SetAutoSpawnOnConnect(false);
    }

    public IPlayer GetPlayerFromNameOrId(string nameOrId)
    {
      Player player;
      if (int.TryParse(nameOrId, out var playerId))
      {
        player = NAPI.Pools.GetAllPlayers().Where(u => u.Handle.Value == playerId).FirstOrDefault();
      }
      else
      {
        player = NAPI.Player.GetPlayerFromName(nameOrId);
      }

      if (player == null || player.Handle == null)
      {
        return null;
      }

      return new RagePlayer(player);
    }

    public void SetTime(int hour, int minute, int second)
    {
      NAPI.World.SetTime(hour, minute, second);
    }

    public void TriggerClientEventForAll(string eventName, params object[] args)
    {
      NAPI.ClientEvent.TriggerClientEventForAll("SERVER:" + eventName, args);
    }

    public TEntity ToEntity<TEntity>(ushort handle) where TEntity : class, IEntity
    {
      return typeof(TEntity).Name switch
      {
        "IPlayer" => new RagePlayer(new NetHandle(handle, EntityType.Player).Entity<Player>()) as TEntity,
        "IVehicle" => new RageVehicle(new NetHandle(handle, EntityType.Vehicle).Entity<Vehicle>()) as TEntity,
        "IMarker" => new RageMarker(new NetHandle(handle, EntityType.Marker).Entity<Marker>()) as TEntity,
        "ITextLabel" => new RageTextLabel(new NetHandle(handle, EntityType.TextLabel).Entity<TextLabel>()) as TEntity,
        "IColShape" => new RageColShape(new NetHandle(handle, EntityType.Colshape).Entity<ColShape>()) as TEntity,
        _ => null,
      };
    }
  }
}
