using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
using Newtonsoft.Json;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Job;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Types;
using ReallifeGamemode.Server.Util;
using ReallifeGamemode.Services;
using System.Buffers;
using Microsoft.EntityFrameworkCore;
using ReallifeGamemode.Server.Events;
using System;

/**
* @overview Life of German Reallife - Managers Interaction (InteractionManager.cs)
* @author VegaZ
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Managers
{
  public class InteractionManager : Script
  {
    #region Eigeninteraktionen Taste-M

    [RemoteEvent("CLIENT:InteractionMenu_AcceptInvite")]
    public void InteractionMenuAcceptInvite(Player player, string type)
    {
      if (type != "Fraktion" && type != "Gruppe") return;

      if (type == "Fraktion") // Fraktions Invite annehmen
      {
        if (!player.HasData("accept_faction_invite"))
        {
          ChatService.ErrorMessage(player, "Du hast keine Einladung in eine Fraktion erhalten");
          return;
        }

        Player leader = NAPI.Player.GetPlayerFromName(player.GetData<string>("accept_faction_invite"));
        player.ResetData("accept_faction_invite");

        if (leader == null)
        {
          ChatService.ErrorMessage(player, "Die Einladung ist abgelaufen");
          return;
        }

        using (var dbContext = new DatabaseContext(true))
        {
          User u = leader.GetUser(dbContext);
          User own = player.GetUser(dbContext);

          FactionHelper.ResetPlayer(player, own, dbContext);

          own.Faction = u.Faction;
          own.FactionLeader = false;
          own.FactionRank = dbContext
              .FactionRanks
              .OrderBy(x => x.Order)
              .Where(r => r.FactionId == own.FactionId)
              .FirstOrDefault();

          ChatService.SendMessage(leader, "!{02FCFF}" + player.Name + " hat die Einladung angenommen.");
          ChatService.SendMessage(player, "!{02FCFF}Du hast die Einladung angenommen.");

          switch (own.FactionId)
          {
            default:
              player.SetSharedData("blipColor", 0);
              break;

            case 8:
              player.SetSharedData("blipColor", 83);
              break;

            case 7:
              player.SetSharedData("blipColor", 52);
              break;

            case 4:
              player.SetSharedData("blipColor", 5);
              break;
          }

          dbContext.SaveChanges();
        }
      }
      else if (type == "Gruppe") // Gruppen Einladung annehmen
      {
        if (!player.HasData("accept_group_invite"))
        {
          ChatService.ErrorMessage(player, "Du hast keine Einladung in eine Gruppe erhalten");
          return;
        }

        Player leader = NAPI.Player.GetPlayerFromName(player.GetData<string>("accept_group_invite"));
        player.ResetData("accept_group_invite");

        if (leader == null)
        {
          ChatService.ErrorMessage(player, "Die Einladung ist abgelaufen");
          return;
        }

        using (var dbContext = new DatabaseContext())
        {
          User u = leader.GetUser(dbContext);
          User own = player.GetUser(dbContext);

          own.Group = u.Group;
          own.GroupRank = GroupRank.MEMBER;

          ChatService.SendMessage(leader, "!{02FCFF}" + player.Name + " hat die Einladung angenommen.");
          ChatService.SendMessage(player, "!{02FCFF}Du hast die Einladung angenommen.");

          dbContext.SaveChanges();
        }
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_EndShow")]
    public void InteractionMenuEndShow(Player client)
    {
      client.ResetData("ShowActive");
    }

    [RemoteEvent("CLIENT:InteractionMenu_Show")]
    public void InteractionMenuShow(Player player, string type, string nameOrId)
    {
      if (type != "License")
        return;

      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }

      User targetUser = target.GetUser();
      User playerUser = player.GetUser();

      if (type == "License")
      {
        if (!playerUser.DriverLicenseBike && !playerUser.DriverLicenseVehicle && !playerUser.FlyingLicensePlane && !playerUser.WeaponLicense)
        {
          player.SendNotification("~r~Sie besitzen keine Scheine!");
          return;
        }
        if (player.Position.DistanceTo(target.Position) > 5)
          return;

        if (target.HasData("ShowActive"))
        {
          player.SendNotification("Spieler ist beschäftigt.");
          return;
        }
        target.SetData("ShowActive", true);
        List<bool> licenses = new List<bool>();
        licenses.Add(playerUser.DriverLicenseVehicle);
        licenses.Add(playerUser.DriverLicenseBike);
        licenses.Add(playerUser.FlyingLicensePlane);
        licenses.Add(playerUser.WeaponLicense);
        target.TriggerEvent("ShowLicenses", player.Name, licenses.ToArray());
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_Invite")]
    public void InteractionMenuInviteFaction(Player player, string type, string nameOrId)
    {
      if (type != "Fraktion" && type != "Gruppe") return;

      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }

      User targetUser = target.GetUser();
      User playerUser = player.GetUser();

      if (type == "Fraktion")
      {
        if (playerUser?.FactionId == null || playerUser?.FactionLeader == false)
        {
          ChatService.NotAuthorized(player);
          return;
        }

        if (targetUser?.FactionId != null)
        {
          ChatService.ErrorMessage(player, "Dieser Spieler ist schon in einer Fraktion");
          return;
        }

        target.SetData("accept_faction_invite", player.Name);

        ChatService.SendMessage(player, "!{02FCFF}Du hast dem Spieler " + target.Name + " eine Einladung in deine Fraktion gesendet.");
        ChatService.SendMessage(target, "!{02FCFF}Du hast von " + player.Name + " eine Einladung in die Fraktion \"" + playerUser.Faction.Name + "\" erhalten.");
        ChatService.SendMessage(target, "!{02FCFF}Benutze das Interaktionsmenü, um die Einladung anzunehmen");
      }
      else if (type == "Gruppe")
      {
        if (playerUser?.Group == null || playerUser.GroupRank < GroupRank.MANAGER)
        {
          ChatService.NotAuthorized(player);
          return;
        }

        if (targetUser?.Group != null)
        {
          ChatService.ErrorMessage(player, "Dieser Spieler ist schon in einer Gruppe");
          return;
        }

        target.SetData("accept_group_invite", player.Name);

        ChatService.SendMessage(player, "!{02FCFF}Du hast dem Spieler " + target.Name + " eine Einladung in deine Gruppe gesendet.");
        ChatService.SendMessage(target, "!{02FCFF}Du hast von " + player.Name + " eine Einladung in die Gruppe \"" + playerUser.Group.Name + "\" erhalten.");
        ChatService.SendMessage(target, "!{02FCFF}Benutze das Interaktionsmenü, um die Einladung anzunehmen");
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_Uninvite")]
    public void InteractionMenuInviteGroup(Player player, string type, string name)
    {
      if (type != "Fraktion" && type != "Gruppe") return;

      Player target = PlayerService.GetPlayerByNameOrId(name);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }

      User targetUser = target.GetUser();
      User playerUser = player.GetUser();

      if (type == "Fraktion")
      {
        if (playerUser?.FactionId == null || playerUser.FactionLeader == false)
        {
          ChatService.NotAuthorized(player);
          return;
        }

        if (targetUser?.FactionId != playerUser?.FactionId)
        {
          ChatService.ErrorMessage(player, "Dieser Spieler ist nicht in deiner Fraktion");
          return;
        }

        if (player.Handle == target.Handle)
        {
          ChatService.ErrorMessage(player, "Du kannst dich nicht selber uninviten");
          return;
        }

        if (targetUser?.FactionLeader ?? false)
        {
          ChatService.ErrorMessage(player, "Du kannst keinen Leader uninviten");
          return;
        }

        using (var dbContext = new DatabaseContext())
        {
          target.SetData("duty", false);
          target.TriggerEvent("toggleDutyMode", false);
          NAPI.ClientEvent.TriggerClientEventForAll("updateDutyMedics", false);
          target.SetSharedData("blipColor", 0);
          UpdateCharacterCloth.LoadCharacterDefaults(target);
          target.GetUser(dbContext).FactionRankId = null;
          target.GetUser(dbContext).FactionId = null;
          ChatService.SendMessage(player, "!{02FCFF}Du hast " + target.Name + " aus der Fraktion geworfen.");
          ChatService.SendMessage(target, "!{02FCFF}Du wurdest von " + player.Name + " aus der Fraktion geworfen.");
          target.SetSharedData("blipColor", 0);
          dbContext.SaveChanges();
        }
      }
      else if (type == "Gruppe")
      {
        if (playerUser?.Group == null || playerUser.GroupRank < GroupRank.MANAGER)
        {
          ChatService.NotAuthorized(player);
          return;
        }

        if (targetUser?.Group.Id != playerUser?.Group.Id)
        {
          ChatService.ErrorMessage(player, "Dieser Spieler ist nicht in deiner Fraktion");
          return;
        }

        if (player.Handle == target.Handle)
        {
          ChatService.ErrorMessage(player, "Du kannst dich nicht selber uninviten");
          return;
        }

        if (targetUser?.GroupRank >= GroupRank.MANAGER && playerUser?.GroupRank != GroupRank.OWNER)
        {
          ChatService.ErrorMessage(player, "Du kannst keinen Leader uninviten");
          return;
        }

        using (var dbContext = new DatabaseContext())
        {
          target.GetUser(dbContext).Group = null;
          target.GetUser(dbContext).GroupRank = GroupRank.NONE;

          ChatService.SendMessage(player, "!{02FCFF}Du hast " + target.Name + " aus der Gruppe geworfen.");
          ChatService.SendMessage(target, "!{02FCFF}Du wurdest von " + player.Name + " aus der Gruppe geworfen.");

          dbContext.SaveChanges();
        }
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_CallService_Taxi")]
    public void CallServiceTaxi(Player player, string street, string zone)
    {
      var taxiJob = JobManager.GetJob<TaxiDriverJob>();

      if (taxiJob.TaxiContracts.Where(t => t.Name == player.Name).Count() != 0)
      {
        ChatService.ErrorMessage(player, "Du kannst nur einmal ein Taxi rufen");
        return;
      }

      taxiJob.TaxiContracts.Add(new TaxiContract()
      {
        Name = player.Name,
        Position = player.Position
      });

      string msg = $"!{{02FCFF}}{player.Name} hat in der Straße {street} in {zone} ein Taxi gerufen.";
      ChatService.BroadcastJob(msg, taxiJob);
      ChatService.SendMessage(player, "!{02FCFF}Du hast erfolgreich ein Taxi zu deiner aktuellen Position gerufen.");
    }

    [RemoteEvent("CLIENT:InteractionMenu_PlayerVehicleInteraction")]
    public void PlayerVehicleInteraction(Player player, int id, string selection)
    {
      using var dbContext = new DatabaseContext(true);
      var user = player.GetUser(dbContext);

      var userVehicle = dbContext.UserVehicles.Where(v => v.Id == id && v.UserId == user.Id).FirstOrDefault();
      if (userVehicle == null)
      {
        ChatService.ErrorMessage(player, "Das Fahrzeug wurde nicht gefunden");
      }

      GTANetworkAPI.Vehicle veh = VehicleManager.GetVehicleFromServerVehicle(userVehicle);

      if (selection == "Finden")
      {
        player.TriggerEvent("SERVER:Util_setWaypoint", veh.Position.X, veh.Position.Y);
      }
      else if (selection == "Verkaufen")
      {
        var vehPrice = userVehicle.Price;
        var backPrice = (int)(vehPrice * 0.6);

        user.BankAccount.Balance += backPrice;

        ChatService.SendMessage(player, $"~b~[INFO]~s~ Du hast durch den Autoverkauf ~g~{backPrice.ToMoneyString()}~s~ erhalten.");

        dbContext.UserVehicles.Remove(userVehicle);
        dbContext.SaveChanges();

        veh.Delete();
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_FactionVehicleInteraction")]
    public void FactionVehicleInteraction(Player player, int id, string selection)
    {
      using var dbContext = new DatabaseContext(true);
      var user = player.GetUser(dbContext);

      var factionVehicle = dbContext.FactionVehicles.ToList().Where(v => v.Id == id && v.GetOwners().Contains(user.FactionId.Value)).FirstOrDefault();
      if (factionVehicle == null)
      {
        ChatService.ErrorMessage(player, "Das Fahrzeug wurde nicht gefunden");
      }

      GTANetworkAPI.Vehicle veh = VehicleManager.GetVehicleFromServerVehicle(factionVehicle);

      if (selection == "Finden")
      {
        player.TriggerEvent("SERVER:Util_setWaypoint", veh.Position.X, veh.Position.Y);
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_FactionVehicleInteractionSell")]
    public void FactionVehicleInteractionSell(Player player, int id, string selection)
    {
      using var dbContext = new DatabaseContext(true);
      var user = player.GetUser(dbContext);

      var factionVehicle = dbContext.FactionVehicles.ToList().Where(v => v.Id == id && v.GetOwners().Contains(user.FactionId.Value)).FirstOrDefault();
      if (factionVehicle == null)
      {
        ChatService.ErrorMessage(player, "Das Fahrzeug wurde nicht gefunden");
      }

      GTANetworkAPI.Vehicle veh = VehicleManager.GetVehicleFromServerVehicle(factionVehicle);

      if (selection == "Verkaufen")
      {
        if (dbContext.FactionVehicles.ToList().Where(f => f.GetOwners().Contains(user.FactionId.Value)).Count() <= 6)
        {
          ChatService.ErrorMessage(player, "Die Fraktion muss mindestens 6 Fahrzeuge besitzen");
          return;
        }

        if (factionVehicle.Model == VehicleHash.Policet || factionVehicle.Model == VehicleHash.Burrito3)
        {
          ChatService.ErrorMessage(player, "Der WT kann nicht verkauft werden");
          return;
        }

        var backPrice = factionVehicle.BuyPrice;

        user.Faction.BankAccount.Balance += backPrice;

        ChatService.SendMessage(player, $"~b~[INFO]~s~ Deine Fraktion hat durch den Autoverkauf ~g~{backPrice.ToMoneyString()}~s~ erhalten.");

        dbContext.FactionVehicles.Remove(factionVehicle);
        dbContext.SaveChanges();

        veh.Delete();
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_LSPD_Ticket3")]
    public void InteractionMenu_LSPD_Ticket3(Player player, string jsonNameOrId, string stringAmount, string jsonReason)
    {
      string nameOrId = (string)JsonConvert.DeserializeObject(jsonNameOrId);
      int amount = Int32.Parse(stringAmount);
      string reason = (string)JsonConvert.DeserializeObject(jsonReason);
      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);
      string playername = NAPI.Player.GetPlayerName(player);
      string targetname = NAPI.Player.GetPlayerName(target);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }
      else if (target == player)
      {
        player.SendNotification("~r~Du kannst dir selbst kein Ticket geben!");
      }
      else
      {
        if (amount > 0 && amount <= 10000)
        {
          player.SendNotification($"~w~Du hast ~y~{targetname} ~w~ein Ticket in Höhe von ~b~{amount}$ ~w~gestellt. Grund: ~g~{reason}~w~.");
          target.SendNotification($"~b~{player.GetUser().FactionRank.RankName} | {playername} ~w~hat dir ein Ticket in Höhe von ~y~{amount}$ ~w~gestellt.", true);
          target.SendNotification($"~w~Grund: ~g~{reason}~w~. ~x~Strafticket im Interaktionsmenü annehmen.", true);
          target.SetData("ticket_boolean", true);
          target.SetData<int>("ticket_amount", amount);
          target.SetData<Player>("ticket_player", player);
        }
        else
        {
          player.SendNotification("~r~Du kannst nur zwischen 1$ und 10000$ angeben!");
        }
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_LSPD_Points3")]
    public void InteractionMenu_LSPD_Points3(Player player, string jsonNameOrId, string jsoAmount, string jsonReason)
    {
      string nameOrId = (string)JsonConvert.DeserializeObject(jsonNameOrId);
      int amount = Int32.Parse((string)JsonConvert.DeserializeObject(jsoAmount));
      string reason = (string)JsonConvert.DeserializeObject(jsonReason);
      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);
      string playername = NAPI.Player.GetPlayerName(player);
      string targetname = NAPI.Player.GetPlayerName(target);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }
      else if (target.GetUser().DriverLicenseVehicle == false && target.GetUser().DriverLicenseBike == false)
      {
        player.SendNotification("~r~Spieler hat weder Auto- noch Motorradführerschein!");
      }
      else if (target == player)
      {
        player.SendNotification("~r~Du kannst dir selbst keine Punkte setzen!");
      }
      else
      {
        if (amount > -9 && amount < 9)
        {
          using (var dbContext = new DatabaseContext())
          {
            User target2 = target.GetUser(dbContext);
            target2.Points += amount;
            dbContext.SaveChanges();
          }
          player.SendNotification($"~w~Du hast ~y~{targetname} ~b~{amount} ~w~Strafpunkte gegeben. Grund: ~g~{reason}~w~.");
          target.SendNotification($"~b~{player.GetUser().FactionRank.RankName} | {playername} ~w~hat dir ~y~{amount} ~w~Strafpunkte gegeben.", true);
          if (target.GetUser().Points < 0)
          {
            using (var dbContext = new DatabaseContext())
            {
              User target2 = target.GetUser(dbContext);
              target2.Points = 0;
              dbContext.SaveChanges();
            }
          }
          else if (target.GetUser().Points >= 8)
          {
            target.SendNotification($"~w~Grund: ~g~{reason}~w~. ~x~Du hast nun ~r~8/8 ~x~Strafpunkten.", true);
            target.SendNotification($"~w~Dir wird ~r~Auto- ~w~und ~r~Motorradführerschein ~w~entzogen.", true);
            foreach (var copPlayer in NAPI.Pools.GetAllPlayers())
            {
              User copUser = copPlayer.GetUser();
              if (copUser.FactionId == 1 || copUser.FactionId == 3)
              {
                if (copUser.GetData<bool>("duty") == true)
                {
                  ChatService.SendMessage(copPlayer, "!{#8181E9}HQ: " + targetname + " besitzt nun keinen Führerschein mehr.");
                }
              }
            }
            using (var dbContext = new DatabaseContext())
            {
              User target2 = target.GetUser(dbContext);
              target2.Points = 0;
              target2.DriverLicenseVehicle = false;
              target2.DriverLicenseBike = false;
              dbContext.SaveChanges();
            }
          }
          else
          {
            target.SendNotification($"~w~Grund: ~g~{reason}~w~. ~x~Du hast nun ~y~{target.GetUser().Points}/8 ~x~Strafpunkten.", true);
          }
        }
        else
        {
          player.SendNotification("~r~Du kannst nur zwischen 1 und 8 Punkte verteilen!");
        }
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_Ticket")]
    public void InteractionMenuTicket(Player target, string type, int ticket_amount)
    {
      Player player = NAPI.Data.GetEntityData(target, "ticket_player");
      string playername = NAPI.Player.GetPlayerName(player);
      string targetname = NAPI.Player.GetPlayerName(target);
      /*if (type != "Fraktion" && type != "Gruppe") return;

      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);
      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }*/

      //User targetUser = target.GetUser();
      //User playerUser = player.GetUser();

      if (type == "Angenommen")
      {
        target.SendNotification($"~g~Du hast das Ticket über ~b~{ticket_amount}$ ~g~angenommen und bezahlt.", true);
        player.SendNotification($"~y~{targetname} ~g~hat das Ticket über ~b~{ticket_amount}$ ~g~angenommen und bezahlt.", true);
        using (var dbContext = new DatabaseContext())
        {
          target.GetUser(dbContext).BankAccount.Balance -= ticket_amount;
          if (player.GetUser().FactionId == 1)
          {
            dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 1).First().BankAccount.Balance += (int)(ticket_amount / 100 * 70);
            dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 3).First().BankAccount.Balance += (int)(ticket_amount / 100 * 30);
          }
          if (player.GetUser().FactionId == 1)
          {
            dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 3).First().BankAccount.Balance += (int)(ticket_amount / 100 * 70);
            dbContext.Factions.Include(f => f.BankAccount).Where(f => f.Id == 1).First().BankAccount.Balance += (int)(ticket_amount / 100 * 30);
          }
          dbContext.SaveChanges();
        }
        target.ResetData("ticket_boolean");
        target.ResetData("ticket_amount");
        target.ResetData("ticket_player");
      }
      else if (type == "Abgelehnt")
      {
        target.SendNotification($"~r~Du hast das Ticket über ~b~{ticket_amount}$ ~r~abgelehnt.", true);
        player.SendNotification($"~y~{targetname} ~r~hat das Ticket über ~b~{ticket_amount}$ ~r~abgelehnt.", true);
        target.ResetData("ticket_boolean");
        target.ResetData("ticket_amount");
        target.ResetData("ticket_player");
      }
    }

    [RemoteEvent("CLIENT:InteractionMenu_Pay")]
    public void InteractionMenu_Pay(Player player, string jsonNameOrId, string stringAmount)
    {
      string nameOrId = (string)JsonConvert.DeserializeObject(jsonNameOrId);
      int amount = Int32.Parse(stringAmount);
      Player target = PlayerService.GetPlayerByNameOrId(nameOrId);

      List<Player> nearbyPlayers = NAPI.Player.GetPlayersInRadiusOfPlayer(3, player);

      if (target == null || !target.IsLoggedIn())
      {
        ChatService.PlayerNotFound(player);
        return;
      }
      else if (target == player)
      {
        player.SendNotification("~r~Du kannst dir selber kein Geld geben!");
      }
      else if (!nearbyPlayers.Contains(target))
      {
        player.SendNotification("~r~Dieser Spieler befindet sich nicht in deiner nähe!");
      }
      else if (player.GetUser().Handmoney < amount)
      {
        player.SendNotification("~r~Du hast nicht genug Geld.");
        return;
      }
      else
      {
        string playername = NAPI.Player.GetPlayerName(player);
        string targetname = NAPI.Player.GetPlayerName(target);

        if (amount > 0 && amount <= 5000)
        {
          player.SendNotification($"~w~Du hast ~y~{targetname} ~w~ ${amount} gegeben.");
          target.SendNotification($"~w~ Du hast von ~y~{playername} ~w~ ${amount} erhalten.", true);

          using (var dbContext = new DatabaseContext())
          {
            target.GetUser(dbContext).Handmoney += amount;
            player.GetUser(dbContext).Handmoney -= amount;
            dbContext.SaveChanges();
          }
        }
        else
        {
          player.SendNotification("~r~ Du kannst nur zwischen $1 und $5.000 geben!");
        }
      }
    }


    #endregion Eigeninteraktionen PFEILTASTE-RUNTER

    #region Spielerinteraktionen PFEILTASTE-LINKS

    [RemoteEvent("openTradeInventory")]
    public void OpenTradeInventory(Player player, string targetPlayer)
    {
      InventoryManager.GetUserItems(player);
      player.TriggerEvent("openTradeMenu", targetPlayer);
    }

    [RemoteEvent("sendTradeItemsToPartner")]
    public void SendTradeItemsToPartner(Player player, string tradeItemArray, int tradePrize, string tradePartnerName)
    {
      var tradeItems = JsonConvert.DeserializeObject<string[][]>(tradeItemArray);
      Player tradePartner = PlayerService.GetPlayerByNameOrId(tradePartnerName);
      InventoryManager.GetUserItems(player);
      tradePartner.TriggerEvent("showTradeRequest", player.Name, tradeItems, tradePrize);
      player.TriggerEvent("startTradeRequestTimer");
    }

    [RemoteEvent("tradeDecision")]
    public void TradeDecision(Player player, string tradeSelection, string tradeItemArray, string tradeRequesterName, int tradePrize)
    {
      var tradeItems = JsonConvert.DeserializeObject<string[][]>(tradeItemArray);
      Player tradeRequester = PlayerService.GetPlayerByNameOrId(tradeRequesterName);
      if (tradeSelection == "accept")
      {
        if (player.GetUser().Handmoney < tradePrize)
        {
          tradeRequester.TriggerEvent("unlockTradeItems");
          tradeRequester.SendNotification("~y~" + player.Name + " ~r~hat nicht genügend Bargeld! ~s~Handel abgebrochen.");
          player.SendNotification("~r~Du hast nicht genügend Bargeld! ~s~Handel abgebrochen.");
        }
        else
        {
          InventoryManager.GetUserItems(player);
          tradeRequester.TriggerEvent("clearTradeItems");
          player.TriggerEvent("showTradeItems", tradeItemArray);

          using (var dbContext = new DatabaseContext())
          {
            var playerUserId = player.GetUser().Id;
            var tradeRUserId = tradeRequester.GetUser().Id;
            var playerUser = dbContext.Users.FirstOrDefault(u => u.Id == playerUserId);
            var tradeRequesterUser = dbContext.Users.FirstOrDefault(u => u.Id == tradeRUserId);

            playerUser.Handmoney -= tradePrize;
            player.TriggerEvent("SERVER:WORLD_INTERACTION:UPDATE_HANDMONEY", playerUser.Handmoney);

            tradeRequesterUser.Handmoney += tradePrize;
            tradeRequester.TriggerEvent("SERVER:WORLD_INTERACTION:UPDATE_HANDMONEY", tradeRequesterUser.Handmoney);

            dbContext.SaveChanges();
          }
        }
      }
      else
      {
        tradeRequester.TriggerEvent("unlockTradeItems");
      }
    }

    #endregion Spielerinteraktionen PFEILTASTE-LINKS
  }
}
