using System;
using GTANetworkAPI;
using ReallifeGamemode.Database;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Factions.Medic;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Server.Types;
using ReallifeGamemode.Server.Util;
using ReallifeGamemode.Server.Wanted;

/**
* @overview Life of German Reallife - Events Death (Death.cs)
* @author VegaZ
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Events
{
  public class Death : Script
  {
    [ServerEvent(Event.PlayerDeath)]
    public void OnPlayerDeath(Player player, Player killer, uint reason)
    {
      if (!player.IsLoggedIn()) player.Kick();
      player.SetData("isDead", true);

      //TODO: Zum Full Release entfernen
      ChatService.SendMessage(player, "Du bist durch " + (killer?.Name ?? "Niemanden") + " gestorben: " + reason.ToString());

      int? killerId;
      float killerPosX;
      float killerPosY;
      float killerPosZ;
      float killerHeading;

      if (killer == null || killer.IsNull)
      {
        killerId = null;
        killerPosX = -1;
        killerPosY = -1;
        killerPosZ = -1;
        killerHeading = -1;
      }
      else
      {
        killerId = killer.GetUser().Id;
        killerPosX = killer.Position.X;
        killerPosY = killer.Position.Y;
        killerPosZ = killer.Position.Z;
        killerHeading = killer.Heading;
        if (player.HasData("inGangWar") && killer.HasData("inGangWar"))
        {
          Gangwar.Gangwar.GangwarKill(killer, player);
        }

        if (player != killer)
        {
          Autowanted.Check_AutoWanted(killer, player);
          string message = "~y~[HINWEIS]: " + killer.Name + " hat " + player.Name + " getötet (" + Managers.WeaponManager.GetCauseOfDeathByHash(reason) + ")";
          ChatService.BroadcastAdmin(message, AdminLevel.ADMIN);
        }
      }

      User user = player.GetUser();
      if (user.JailTime <= 0)
      {
        if(user.Wanteds > 0)
        {
          ChatService.BroadcastFaction("!{#8181E9}HQ: Der Verdächtigte " + player.Name + " wurde soeben ins Krankenhaus eingeliefert.", new System.Collections.Generic.List<int>() { 1, 3 });
        }
        //MEDIC AUFTRAG
        MedicTask reviveTask = new MedicTask()
        {
          Victim = player.Name,
          Position = player.Position,
          CauseOfDeath = reason.ToString(),
          Caller = null,
          Description = "Gestorben",
          Time = DateTime.Now,
          Type = MedicTaskType.REVIVE,
          MedicName = "none"
        };
        Medic.AddTaskToList(reviveTask);

        if (player.GetUser().IsAdmin(AdminLevel.ADMIN) == true)
        {
          player.TriggerEvent("startDeathTimer", true);
        }
        else
        {
          player.TriggerEvent("startDeathTimer", false);
        }

        //TODO PICTURE NOTIFICATION + SOUND für Medics

        using (var userDeath = new DatabaseContext())
        {
          var dead = new Database.Entities.Logs.Death
          {
            VictimId = player.GetUser().Id,
            KillerId = killerId,
            KillerPositionX = killerPosX,
            KillerPositionY = killerPosY,
            KillerPositionZ = killerPosZ,
            KillerHeading = killerHeading,
            VictimPositionX = player.Position.X,
            VictimPositionY = player.Position.Y,
            VictimPositionZ = player.Position.Z,
            VictimHeading = player.Heading,
            CauseOfDeath = reason.ToString()
          };
          userDeath.DeathLogs.Add(dead);
          userDeath.SaveChanges();
        }
      }

      //JailTime.cs
      Jail.Check_PutBehindBars(player);
    }


    [RemoteEvent("RespawnPlayerAtHospital")]
    public void RespawnPlayerAtHospital(Player player)
    {
      player.SetData("isDead", false);
      player.RemoveAllWeapons();
      NAPI.Player.SpawnPlayer(player, new Vector3(-495.45, -336.33, 34.5));
    }
  }
}
