using System;
using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Services;

/**
* @overview Life of German Reallife - Player Extension (PlayerExtension.cs)
* @author hydrant, Siga, aviate
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Extensions
{
  public static class PlayerExtension
  {
    /// <summary>
    /// Gibt das User-Objekt eines Player's zurück.
    /// Gibt nichts zurück, wenn der Player nicht eingeloggt ist
    /// </summary>
    /// <param name="client">Der Player, dessen User man bekommen möchte</param>
    /// <param name="context">Ein eventuell vorhandener Datenbank-Context, falls man Änderungen in der Datenbank vornehmen will</param>
    /// <returns></returns>
    public static User GetUser(this Player client, DatabaseContext context = null)
    {
      context = context ?? new DatabaseContext();
      if (!client.IsLoggedIn()) return null;
      return context
          .Users
          .Include(u => u.Faction)
            .ThenInclude(f => f.BankAccount)
          .Include(u => u.FactionRank)
          .Include(u => u.Group)
          .Include(u => u.House)
          .Include(u => u.BankAccount)
          .Where(u => u.Name == client.Name)
          .FirstOrDefault();
    }

    public static Character GetCharacter(this User user, DatabaseContext context = null)
    {
      if (context == null)
      {
        using (context = new DatabaseContext())
        {
          return context.Characters.FirstOrDefault(u => u.UserId == user.Id);
        }
      }
      else
      {
        return context.Characters.FirstOrDefault(u => u.UserId == user.Id);
      }
    }

    /// <summary>
    /// Gibt zurück, ob ein Player eingeloggt ist
    /// </summary>
    /// <param name="player">Der Player, dessen Login-Status man bekommen möchte</param>
    /// <returns></returns>
    public static bool IsLoggedIn(this Player player)
    {
      if (player == null)
      {
        return false;
      }

      return player.HasData("isLoggedIn") ? player.GetData<bool>("isLoggedIn") : false;
    }

    public static bool IsDuty(this Player player)
    {
      var user = player.GetUser();
      return user.GetData("duty", false);
    }
    public static bool IsAdminDuty(this Player player)
    {
      return player.HasData("Adminduty") ? player.GetData<bool>("Adminduty") : false;
    }
    public static Vector3 GetPositionFromPlayer(Player player, float distance, int offset = 0)
    {
      var pos = player.Position;
      var a = player.Heading + offset;
      var rad = a * Math.PI / 180;
      var newpos = new Vector3(pos.X + (distance * Math.Sin(-rad)),
          pos.Y + (distance * Math.Cos(-rad)),
          pos.Z);
      return newpos;
    }

    internal static T GetData<T>(this User user, string key, T nullValue)
    {
      key += "data_";
      if (!user.Player.HasData(key)) return nullValue;
      return JsonConvert.DeserializeObject<T>(user.Player.GetData<dynamic>(key));
    }

    internal static T GetData<T>(this User user, string key) => user.GetData<T>(key, default);

    internal static void SetData(this User user, string key, object value)
    {
      key += "data_";
      user.Player.SetData(key, JsonConvert.SerializeObject(value));
    }

    internal static void GiveWanteds(this User user, Player cop, int amount, string reason)
    {
      if (user.Wanteds + amount > 50)
      {
        ChatService.ErrorMessage(cop, "Die Wanteds dürfen ein Limit von 50 nicht überschreiten");
        return;
      }
      int newWanteds = user.Wanteds + amount;
      using (var dbContext = new DatabaseContext())
      {
        User dbUser = dbContext.Users.Where(u => u.Id == user.Id).FirstOrDefault();
        dbUser.Wanteds = newWanteds;
        dbContext.SaveChanges();
      }
      user.Player.SetSharedData("blipColor", 64);
      ChatService.SendMessage(user.Player, "!{#FF614A}Du hast ein Verbrechen begangen: " + reason + "" + (cop != null ? " | Gemeldet von: " + cop.Name + "." : ""));
      ChatService.SendMessage(user.Player, "  !{#FFFF00}Fahnundgslevel:~s~ " + newWanteds);

      foreach (var copPlayer in NAPI.Pools.GetAllPlayers())
      {
        if (copPlayer == null)
        {
          continue;
        }

        User copUser = copPlayer.GetUser();
        if (cop != null && (copUser.FactionId == 1 || copUser.FactionId == 3))
        {
          ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: Straftat gemeldet von " + cop.Name + " mit Fahndungslevel " + amount + ". Straftäter: " + user.Name + ".");
          ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: Grund: " + reason + ".");
          ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: Der Straftäter: " + user.Name + " wird nun mit Fahndungslevel " + newWanteds + " gesucht.");
        }
        else if ((copUser.FactionId == 1 || copUser.FactionId == 3) && cop == null)
        {
          ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: " + user.Name + " hat eine Straftat begangen. Grund: " + reason + ".");
          ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: Der Straftäter: " + user.Name + " wird nun mit Fahndungslevel " + newWanteds + " gesucht.");
        }
      }
    }

    public static FactionRank GetFactionRank(this User user)
    {
      using (var dbContext = new DatabaseContext())
      {
        FactionRank toReturn = dbContext.FactionRanks.FirstOrDefault(fR => fR.Id == user.FactionRankId);
        if (toReturn == null)
        {
          toReturn = dbContext.FactionRanks.OrderBy(f => f.Order).FirstOrDefault(f => f.FactionId == user.FactionId);
        }

        if (toReturn == null)
        {
          toReturn = new FactionRank
          {
            RankName = "Rang-Fehler"
          };
        }

        return toReturn;
      }
    }

    public static void BanPlayer(this User user, Player admin, string reason, int mins)
    {
      using (var banUserContext = new DatabaseContext())
      {
        int unixTimestamp = (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
        Ban banUser;

        if (mins == 0)
        {
          ChatService.Broadcast("!{#FF4040}[BAN] " + user.Name + " wurde von " + admin.Name + " permanent gebannt. [" + reason + "]");
          banUser = new Ban { UserId = user.Id, Reason = reason, BannedBy = admin.Name, Applied = unixTimestamp, UntilDateTime = unixTimestamp };

          user.Player?.Kick();

          mins--;
        }
        else
        {
          ChatService.Broadcast("!{#FF4040}[BAN] " + user.Name + " wurde von " + admin.Name + " für " + mins + " Minuten gebannt. [" + reason + "]");
          banUser = new Ban { UserId = user.Id, Reason = reason, BannedBy = admin.Name, Applied = unixTimestamp, UntilDateTime = unixTimestamp + mins * 60 };
          user.Player?.Kick();
        }

        banUserContext.Bans.Add(banUser);
        banUserContext.SaveChanges();

        var targetUser = banUserContext.Users.Where(u => u.Name == user.Name).FirstOrDefault();
        targetUser.BanId = banUser.Id;
        banUserContext.SaveChanges();
      }
    }

    public static void UnbanPlayer(this User user)
    {
      using (var unbanUser = new DatabaseContext())
      {
        var targetUser = unbanUser.Users.Where(u => u.Id == user.Id).FirstOrDefault();
        targetUser.BanId = null;
        unbanUser.SaveChanges();
      }
    }

    public static List<UserItem> GetItems(this User user)
    {
      using (var dbContext = new DatabaseContext())
      {
        return dbContext.UserItems.Where(u => u.UserId == user.Id).ToList();
      }
    }
  }
}
