using System;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
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, bool bankAccount = false, bool faction = false)
    {
      if (player == null)
      {
        return null;
      }

      var user = dbContext.Users.Where(u => u.Name == player.Name);

      if (bankAccount)
      {
        user = user.Include(u => u.BankAccount);
      }

      if (faction)
      {
        user = user.Include(u => u.Faction);
      }

      return user.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;
    }

    public static bool IsLoggedIn(this IPlayer player) => player.GetSharedData("isLoggedIn", false);
  }
}
