using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Factions.Medic;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Wanted;
using ReallifeGamemode.Services;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

/**
* @overview Life of German Reallife - Faction Commands (Faction.cs)
* @author VegaZ, hydrant, aviate
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Commands
{
  class FactionCommands : Script
  {
    #region Chat Commands

    [Command("f", "~m~Benutzung: ~s~/f [Nachricht]", GreedyArg = true)]
    public void CmdFactionF(Player player, string message)
    {
      Faction f = player.GetUser()?.Faction;
      if (f == null || f.StateOwned)
      {
        ChatService.NotAuthorized(player);
        return;
      }

      message = Regex.Replace(message, "(~[a-zA-Z]~)|(!{(.*)})", "");

      string broadcastMessage = "!{02FCFF}** " + player.GetUser().GetFactionRank().RankName + " " + player.Name + ": " + message + " )) **";
      ChatService.BroadcastFaction(broadcastMessage, f);
    }

    [Command("r", "~m~Benutzung: ~s~/r [Nachricht]", GreedyArg = true)]
    public void CmdFactionR(Player player, string message)
    {
      Faction f = player.GetUser()?.Faction;
      if (f == null || !f.StateOwned)
      {
        ChatService.NotAuthorized(player);
        return;
      }

      message = Regex.Replace(message, "(~[a-zA-Z]~)|(!{(.*)})", "");

      string broadcastMessage = "!{33AA33}** " + player.GetUser().GetFactionRank().RankName + " " + player.Name + ": " + message + ", over **";
      ChatService.BroadcastFaction(broadcastMessage, f);
    }

    [Command("d", "~m~Benutzung: ~s~/d [Nachricht]", GreedyArg = true)]
    public void CmdFactionD(Player player, string message)
    {
      Faction f = player.GetUser()?.Faction;
      if (f == null || !f.StateOwned)
      {
        ChatService.NotAuthorized(player);
        return;
      }

      message = Regex.Replace(message, "(~[a-zA-Z]~)|(!{(.*)})", "");

      string broadcastMessage = "!{CC3333}** " + player.GetUser().GetFactionRank().RankName + " " + player.Name + ": " + message + ", over **";
      using (var context = new DatabaseContext())
      {
        ChatService.BroadcastFaction(broadcastMessage, context.Factions.ToList().FindAll(c => c.StateOwned));
      }
    }
    #endregion
    #region Leader Commands
    [Command("giverank", "~m~Benutzung: ~s~/giverank [Name] [Rang]", GreedyArg = true)]
    public void CmdFactionGiverank(Player player, string name, string rank)
    {
      if (player.GetUser()?.FactionId == null || player.GetUser().FactionLeader == false)
      {
        ChatService.NotAuthorized(player);
        return;
      }

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

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

      using (var dbContext = new DatabaseContext())
      {
        FactionRank fr = dbContext.FactionRanks.FirstOrDefault(r => r.Order == int.Parse(rank) && r.FactionId == player.GetUser(dbContext).FactionId);
        if (fr == null)
        {
          ChatService.ErrorMessage(player, "Dieser Rang existiert nicht");
          return;
        }

        target.GetUser(dbContext).FactionRankId = fr.Id;

        ChatService.SendMessage(player, "!{02FCFF}Du hast " + target.Name + " den Rang '" + fr.Order + "(" + fr.RankName +  ")' gegeben.");
        ChatService.SendMessage(target, "!{02FCFF}Du hast von " + player.Name + " den Rang '" + fr.Order + "(" + fr.RankName + ")' erhalten.");

        dbContext.SaveChanges();
      }
    }

    [Command("lc", "~m~Benutzung: ~s~/lc [Nachricht]", GreedyArg = true)]
    public void CmdFactionLc(Player player, string message)
    {
      if (player.GetUser()?.FactionId == null || player.GetUser().FactionLeader == false)
      {
        ChatService.NotAuthorized(player);
        return;
      }

      message = Regex.Replace(message, "(~[a-zA-Z]~)|(!{(.*)})", "");

      string broadcastMsg = "~y~[" + player.GetUser().Faction.Name + "] " + player.Name + ": " + message;

      NAPI.Pools.GetAllPlayers().ForEach(p =>
      {
        if (p.GetUser()?.FactionLeader ?? false) ChatService.SendMessage(p, broadcastMsg);
      });
    }

    [Command("setweaponrank", "~m~Benutzung: ~s~/setweaponrank [Waffen Name] [Rank]")]
    public void CmdFactionWeaponRank(Player player, string weaponModel, int rank)
    {
      if (player.GetUser()?.FactionId == null || player.GetUser().FactionLeader == false)
      {
        ChatService.NotAuthorized(player);
        return;
      }
      if (rank > 12 || rank < 1)
      {
        ChatService.ErrorMessage(player, "Gebe einen gültigen Rang ein");
        return;
      }

      User user = player.GetUser();
      WeaponPoint nearestWeapon = PositionManager.WeaponPoints.Find(w => w.Position.DistanceTo(player.Position) <= 1.5 && w.FactionId == user.FactionId);
      if (nearestWeapon == null)
      {
        ChatService.ErrorMessage(player, "Du bist nicht in der nähe vom Waffenspind");
        return;
      }

      using (var context = new DatabaseContext())
      {
        FactionWeapon fw2 = context.FactionWeapons.FirstOrDefault(w => w.FactionId == user.FactionId && w.WeaponModel == weaponModel);

        if (fw2 != null)
        {
          fw2.Rank = rank;
          context.SaveChanges();
          ChatService.SendMessage(player, "Du hast die " + weaponModel + " als Rang " + rank + " Waffe eingestellt.");
          return;
        }
        ChatService.ErrorMessage(player, "Diese Waffe ist nicht im Waffenlager");
        return;
      }
    }


    #endregion
    #region Sanitäter Commands

    [Command("revive", "~m~Benutzung: ~s~/revive")]
    public void CmdFactionMedicRevive(Player player)
    {
      if (player.GetUser()?.FactionId == null || player.GetUser().FactionId != 2)
      {
        ChatService.NotAuthorized(player);
        return;
      }
      if (player.IsInVehicle)
      {
        ChatService.ErrorMessage(player, "Du kannst in einem Auto nicht wiederbeleben");
        return;
      }

      var nearPlayers = NAPI.Player.GetPlayersInRadiusOfPlayer(2, player);
      var deadPlayer = nearPlayers.Where(i => i.GetData<bool>("isDead") == true).FirstOrDefault();
      if (player == deadPlayer)
      {
        ChatService.ErrorMessage(player, "Du kannst dich nicht selbst wiederbeleben");
        return;
      }
      player.PlayAnimation("amb@medic@standing@kneel@enter", "enter", 0);

      deadPlayer.TriggerEvent("onPlayerRevived");
      deadPlayer.SendNotification("Du wurdest von ~r~" + player.Name + "~s~ wiederbelebt.");
      deadPlayer.SetData("isDead", false);
      NAPI.Player.SpawnPlayer(deadPlayer, deadPlayer.Position);
      deadPlayer.Health = 50;

      MedicTask task = Medic.ReviveTasks.FirstOrDefault(t => t.Victim == deadPlayer.Name);
      Medic.RemoveTaskFromList(task);
    }

    [Command("heal", "~m~Benutzung: ~s~/heal [Spieler]")] //TODO Eventuell noch mit Geldbetrag wie bei SA:MP
    public void CmdFactionMedicHealive(Player player, string receiver)
    {
      if (player.GetUser()?.FactionId == null || player.GetUser().FactionId != 2)
      {
        ChatService.NotAuthorized(player);
        return;
      }
      if (player.IsInVehicle)
      {
        ChatService.ErrorMessage(player, "Du kannst in einem Auto nicht heilen");
        return;
      }
      Player target = PlayerService.GetPlayerByNameOrId(receiver);
      target.Health = 100;
      target.SendNotification("Du wurdest von ~g~" + player.Name + " ~s~geheilt.", false);
      player.SendNotification("Du hast ~g~" + target.Name + " ~s~geheilt.", false);
    }
    #endregion
    #region Staatsfraktionen (LSPD / FBI) Commands
    [Command("wanted", "~m~Benutzung: ~s~/wa(nted) [Name / ID] [Anzahl] [Grund]", Alias = "wa", GreedyArg = true)]
    public void CmdFactionWanted(Player player, string nameOrId, int amount, string reason)
    {
      User user = player.GetUser();
      if (user == null || (user.FactionId != 1 && user.FactionId != 3))
      {
        ChatService.NotAuthorized(player);
        return;
      }

      if (amount <= 0)
      {
        ChatService.ErrorMessage(player, "Es muss eine positive Wantedanzahl vergeben werden");
        return;
      }

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

      User targetCop = target.GetUser();
      if (targetCop.FactionId == 1 || targetCop.FactionId == 3)
      {
        ChatService.ErrorMessage(player, "Du kannst dieser Person keine Wanteds geben");
        return;
      }
      User targetUser = target.GetUser();
      targetUser.GiveWanteds(player, amount, reason);
    }

    [Command("clear", "~m~Benutzung: ~s~/clear [Name / ID] [Grund]", GreedyArg = true)]
    public void CmdFactionClear(Player player, string nameOrId, string reason)
    {

      User user = player.GetUser();
      if (user == null || (user.FactionId != 1 && user.FactionId != 3))
      {
        ChatService.NotAuthorized(player);
        return;
      }

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

      using (var dbContext = new DatabaseContext())
      {
        User targetUser = target.GetUser(dbContext);
        if (targetUser.Wanteds == 0)
        {
          ChatService.ErrorMessage(player, "Der Spieler hat keine Wanteds");
          return;
        }
        ChatService.SendMessage(target, "!{#8181E9}Deine Akte wurde von " + player.Name + " gelöscht. Grund: " + reason);
        ChatService.BroadcastFaction("!{#8181E9}HQ: Die Akte von " + target.Name + " wurde von " + player.Name + " gelöscht. Grund: " + reason + ".", new List<int>() { 1, 3 });
        target.SetSharedData("blipColor", 0);
        switch (targetUser.FactionId)
        {
          case 8:
            target.SetSharedData("blipColor", 83);
            break;
          case 7:
            target.SetSharedData("blipColor", 52);
            break;
          case 4:
            target.SetSharedData("blipColor", 5);
            break;
        }
        target.TriggerEvent("jailTime", 0);

        targetUser.Wanteds = 0;
        dbContext.SaveChanges();
      }
    }




    #endregion
    #region Global Fraktions Commands
    #endregion
  }
}
