using System;
using System.Linq;
using System.Linq.Expressions;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Core.API;
using ReallifeGamemode.Server.Types;

namespace ReallifeGamemode.Server.Core.Extensions
{
  public static class PlayerExtensions
  {
    public static User GetUser(this IPlayer player, DatabaseContext dbContext)
    {
      if (player == null)
      {
        return null;
      }

      return dbContext.Users.Where(u => u.Name == player.Name).FirstOrDefault();
    }

    public static AdminLevel GetAdminLevel(this IPlayer player, DatabaseContext dbContext)
    {
      return player.GetData(u => u.AdminLevel, dbContext);
    }

    public static TData GetData<TData>(this IPlayer player, Expression<Func<User, TData>> data, DatabaseContext dbContext)
    {
      if (player == null)
      {
        return default;
      }

      return dbContext.Users.Where(u => u.Name == player.Name).Select(data).FirstOrDefault();
    }

    public static bool IsAdmin(this IPlayer player, AdminLevel level, DatabaseContext dbContext)
    {
      return player.GetAdminLevel(dbContext) >= level;
    }
  }
}
