using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
using Newtonsoft.Json;
using ReallifeGamemode.Server.Classes;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Factions.Medic;
using ReallifeGamemode.Server.Finance;
using ReallifeGamemode.Server.Inventory;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Services;
using ReallifeGamemode.Database;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Util;
using ReallifeGamemode.Server.Inventory.Interfaces;
using ReallifeGamemode.Server.DrivingSchool;
using ReallifeGamemode.Server.Types;
/**
* @overview Life of German Reallife - Event Key (Key.cs)
* @author VegaZ
* @copyright (c) 2008 - 2018 Life of German
*/

namespace ReallifeGamemode.Server.Events
{
  public class Key : Script
  {
    [RemoteEvent("keyPress:NUM2")]
    public void KeyPressNUM2(Player player)
    {
      if (!player.IsLoggedIn()) return;
      if (player.GetData<bool>("editmode") == true && player.GetUser().IsAdmin(AdminLevel.HEADADMIN) == true)
      {
        var saveMode = player.GetData<string>("quicksavemode");
        switch (saveMode)
        {
          case "none":
            ChatService.SendMessage(player, "~r~Keinen Modus ausgewählt! ~y~/quicksavemode ~r~für mehr Infos!");
            break;

          case "blip":
            TempBlip tempBlip = NAPI.Data.GetWorldData("blipTemplate");
            SaveManager.OnSaveBlipData(player, tempBlip.Sprite.ToString(), tempBlip.Name, tempBlip.Scale.ToString(), tempBlip.Color.ToString(),
                tempBlip.Transparency.ToString(), 200.ToString(), tempBlip.ShortRange.ToString(), 0.ToString(), 0.ToString());
            player.SendNotification("~y~Blip~s~ erstellt!", false);
            break;
          case "atm":
            SaveManager.OnSaveBlipData(player, "500", "Geldautomat", 0.7.ToString(), "11",
                "0", "200", true.ToString(), 0.ToString(), 0.ToString());
            player.SendNotification("~y~ATM~s~ erstellt!", false);
            break;
        }
      }

      GroundItem.PickUpGroundItem(player);
    }

    [RemoteEvent("keyPress:UP_ARROW")]
    public void KeyPressUpArrow(Player player)
    {
      if (!player.IsLoggedIn()) return;
      if (player.HasData("nearATM"))
      {
        ATMManager.ShowAtmUi(player, player.GetData<int>("nearATM"));
      }
    }

    [RemoteEvent("keyPress:LEFT_ARROW")]
    public void KeyPressLeftArrow(Player player)
    {
      if (!player.IsLoggedIn()) return;
      List<Player> nearbyPlayers = NAPI.Player.GetPlayersInRadiusOfPlayer(3, player);

      if (nearbyPlayers.Count > 1)
      {
        List<string> nearbyPlayerList = new List<string>();
        foreach (Player nearPlayer in nearbyPlayers)
        {
          if (nearPlayer.Name != player.Name)
          {
            nearbyPlayerList.Add(nearPlayer.Name);
          }
          else
          {
            continue;
          }
        }
        player.TriggerEvent("showPlayerInteraction", JsonConvert.SerializeObject(nearbyPlayerList));
      }
    }

    [RemoteEvent("keyPress:RIGHT_ARROW")]
    public void KeyPressRightArrow(Player player)
    {
      if (!player.IsLoggedIn()) return;
      User user = player.GetUser();
      switch (user.FactionId)
      {
        //LSFD
        case 2:
          player.TriggerEvent("showFactionInteraction", user.FactionId, user.GetData<bool>("duty"), user.Faction.Name, user.FactionLeader, Medic.ReviveTasks.Count.ToString(), Medic.HealTasks.Count.ToString(), Medic.FireTasks.Count.ToString());
          break;
      }
    }

    [RemoteEvent("keyPress:DOWN_ARROW")]
    public void KeyPressDownArrow(Player player)
    {
      User u = player.GetUser();
      if (u == null) return;

      Paycheck paycheck = null;
      if (Economy.Paychecks.ContainsKey(u.Id)) paycheck = Economy.Paychecks[u.Id];

      Licenses licenses = new Licenses(u.DriverLicenseVehicle, u.DriverLicenseBike, u.FlyingLicensePlane, u.WeaponLicense);

      var accountData = new
      {
        regDate = u.RegistrationDate.ToShortDateString(),
        adminLevel = u.AdminLevel.GetName(),
        faction = u.Faction?.Name ?? "Zivilist",
        factionRank = u.GetFactionRank().RankName,
        group = u.Group?.Name ?? "Keine",
        groupRank = u.GroupRank.GetName(),
        job = JobManager.GetJob(u.JobId ?? 0)?.Name ?? "Keiner",
        paycheck,
        licenses
      };

      string faction = u.FactionLeader ? u.Faction.Name : null;
      string group = u.Group != null && u.GroupRank >= GroupRank.MANAGER ? u.Group.Name : null;
      bool factionInvite = player.HasData("accept_faction_invite");
      bool groupInvite = player.HasData("accept_group_invite");

      player.TriggerEvent("SERVER:InteractionMenu_OpenMenu", JsonConvert.SerializeObject(accountData), faction, group, factionInvite, groupInvite);
    }

    [RemoteEvent("keyPress:E")]
    public void KeyPressE(Player player)
    {
      if (!player.IsLoggedIn()) return;
      var user = player.GetUser();


      if (user?.FactionId != null)
      {
        DutyPoint nearestDuty = PositionManager.DutyPoints.Find(d => d.Position.DistanceTo(player.Position) <= 1.5 && d.FactionId == user.FactionId);
        WeaponPoint nearestWeapon = PositionManager.WeaponPoints.Find(w => w.Position.DistanceTo(player.Position) <= 1.5 && w.FactionId == user.FactionId);
        JailReleasePoint nearestJailReleasePoint = PositionManager.JailReleasePoints.Find(j => j.Position.DistanceTo(player.Position) <= 1.5 && (user.FactionId == 1 || user.FactionId == 3) && user.GetData<bool>("duty"));
        ElevatorPoint nearestElevatorPoint = PositionManager.ElevatorPoints.Find(e => e.Position.DistanceTo(player.Position) <= 1.5 && (user.FactionId == 1 || user.FactionId == 3));
        ClotheshopPoint nearestClotheShopPoint = PositionManager.clotheshopPoints.Find(s => s.Position.DistanceTo(player.Position) <= 1.5 && (!user.GetData<bool>("duty")));
        ItemshopPoint nearestItemShopPoint = PositionManager.itemshopPoints.Find(s => s.Position.DistanceTo(player.Position) <= 1.5);

        if (nearestDuty != null)// Duty Point
        {
          var nameTagColor = new Color(0, 0, 0);
          var factionId = user.FactionId;

          if (user.GetData<bool>("duty") == false)
          {
            user.SetData("duty", true);
            player.SendNotification("Du bist nun ~g~im Dienst.");
            player.TriggerEvent("toggleDutyMode", true);
            if (player.GetUser().FactionId == 2) //Fire Department
            {
              int medicCount = 0;
              foreach (Player c in NAPI.Pools.GetAllPlayers())
              {
                if ((c.GetUser()?.Faction?.Id ?? 0) == 2)
                {
                  medicCount++;
                }
              }
              NAPI.ClientEvent.TriggerClientEventForAll("updateDutyMedics", medicCount);
            }
            switch (factionId)
            {
              //LSPD
              case 1:
                nameTagColor = new Color(28, 134, 238);
                player.SetSharedData("blipColor", 38);
                break;

              //Medic
              case 2:
                nameTagColor = new Color(255, 0, 0);
                player.SetSharedData("blipColor", 79);
                break;

              //FBI
              case 3:
                nameTagColor = new Color(173, 0, 118);
                player.SetSharedData("blipColor", 72);
                player.SetAccessories(2, 2, 0);
                break;
            }
            using (var context = new DatabaseContext())
            {
              List<CharacterCloth> clothes = context.CharacterClothes.Where(u => u.UserId == user.Id && u.Duty == true).ToList();

              foreach (var cloth in clothes)
              {
                if (cloth.SlotType == 0)
                {
                  player.SetClothes(cloth.SlotId, cloth.ClothId, 0);
                }
                else
                {
                  if (cloth.ClothId != -1)
                  {
                    player.SetAccessories(cloth.SlotId, cloth.ClothId, 0);
                  }
                  else
                  {
                    player.ClearAccessory(cloth.SlotId);
                  }
                }
              }
            }
          }
          else
          {
            user.SetData("duty", false);
            player.SendNotification("Du bist nun ~r~außer Dienst.");
            player.TriggerEvent("toggleDutyMode", false);
            NAPI.ClientEvent.TriggerClientEventForAll("updateDutyMedics", false);
            player.SetSharedData("blipColor", 0);
            UpdateCharacterCloth.LoadCharacterDefaults(player);
          }
        }
        if (nearestWeapon != null) // Weapon Point
        {

          List<string> primarys = new List<string>();
          List<string> secondarys = new List<string>();
          List<string> melees = new List<string>();
          List<string> specials = new List<string>();
          List<string> timer = new List<string>();
          string dealTime = "Starten";
          primarys.Add("Keine");
          secondarys.Add("Keine");
          melees.Add("Keine");
          specials.Add("Keine");



          using (var context = new DatabaseContext())
          {


            List<UserItem> fItem = context.UserItems.Where(u => u.UserId == user.Id).ToList();
            foreach (var item in fItem)
            {
              IItem iItem = InventoryManager.GetItemById(item.ItemId);
              if (iItem is IWeaponDealItem obj)
              {
                FactionWeapon weapon = context.FactionWeapons.Where(w => w.FactionId == user.FactionId && w.WeaponModel == iItem.Name).FirstOrDefault();
                if (weapon == null)
                  continue;
                weapon.Ammount += item.Amount;
                ChatService.SendMessage(player, item.Amount + " " + iItem.Name + " wurden im Waffenlager hinzugefürgt.");
                context.Remove(item);
              }
            }
            context.SaveChanges();

            List<FactionWeapon> weapons = context.FactionWeapons.Where(w => w.FactionId == user.FactionId).ToList();
            Database.Entities.Faction faction = context.Factions.Where(fac => fac.Id == user.FactionId).FirstOrDefault();

            if (faction.WeaponDealTime > 0)
              dealTime = "noch " + faction.WeaponDealTime.ToString() + " min. übrig";

            timer.Add(dealTime);

            foreach (var weapon in weapons)
            {
              if (weapon.Ammount <= 0)
                continue;
              switch (weapon.SlotID)
              {
                case 1:
                  if (user.FactionRank.Order >= weapon.Rank)
                    primarys.Add(weapon.WeaponModel.ToString());
                  break;
                case 2:
                  if (user.FactionRank.Order >= weapon.Rank)
                    secondarys.Add(weapon.WeaponModel.ToString());
                  break;
                case 3:
                  if (user.FactionRank.Order >= weapon.Rank)
                    melees.Add(weapon.WeaponModel.ToString());
                  break;
                case 4:
                  if (user.FactionRank.Order >= weapon.Rank)
                    specials.Add(weapon.WeaponModel.ToString());
                  break;
              }
            }
          }

          player.TriggerEvent("showWeaponMenu", primarys.ToArray(), secondarys.ToArray(), melees.ToArray(), specials.ToArray(), JsonConvert.SerializeObject(timer.ToArray()));
        }
        if (nearestJailReleasePoint != null)
        {
          List<string> criminals = new List<string>();
          criminals.Add("Keiner");
          foreach (Player target in NAPI.Pools.GetAllPlayers())
          {
            User c = target.GetUser();
            if (c.JailTime > 0)
            {
              criminals.Add(c.Name);
            }
          }
          player.TriggerEvent("showJailMenu", JsonConvert.SerializeObject(criminals.ToArray()));
        }
        if (nearestElevatorPoint != null)
        {
          List<string> stages = new List<string>();
          foreach (var e in PositionManager.ElevatorPoints)
          {
            if (e.Position.DistanceTo2D(player.Position) <= 25 && e.Position.DistanceTo(player.Position) > 1.5)
            {
              stages.Add(e.Stage);
            }
          }
          player.TriggerEvent("showElevatorMenu", JsonConvert.SerializeObject(stages.ToArray()));
        }
        if (nearestClotheShopPoint != null)
        {
          nearestClotheShopPoint.clotheShop.LoadShopNUI(player);
        }
        if (nearestItemShopPoint != null)
        {
          nearestItemShopPoint.itemShop.LoadShopNUI(player);
        }
        if (user.FactionLeader)
        {
          player.TriggerEvent("CLIENT:StartGangwar");
        }
      }
    }

    [RemoteEvent("keyPress:I")]
    public void KeyPressI(Player player)
    {
      if (!player.IsLoggedIn()) return;
      InventoryManager.GetUserItems(player);
    }

    [RemoteEvent("keyPress:O")]
    public void KeyPressJ(Player player)
    {
      if (!player.IsLoggedIn()) return;
      List<Player> players = NAPI.Pools.GetAllPlayers();
      var listPlayers = players.Select(p => new
      {
        Id = p.Handle.Value,
        p.Name,
        p.Ping,
      });
      player.TriggerEvent("showPlayerlist", JsonConvert.SerializeObject(listPlayers));
    }

    [RemoteEvent("keyPress:K")]
    public void KeyPressK(Player player)
    {
      if (!player.IsLoggedIn()) return;
      var user = player.GetUser();
      if (user?.FactionId != null)
      {
        DutyPoint nearest = PositionManager.DutyPoints.Find(d => d.Position.DistanceTo(player.Position) <= 1.5);
        if (nearest == null) return;
        if (player.Position.DistanceTo(nearest.Position) <= 1.5 && nearest.FactionId == user.FactionId)
        {
          List<string> hats = new List<string>();
          List<string> tops = new List<string>();
          List<string> legs = new List<string>();
          List<string> shoes = new List<string>();

          using (var context = new DatabaseContext())
          {
            List<DutyCloth> clothes = context.DutyClothes.ToList().FindAll(c => c.FactionId == user.FactionId && c.Gender == user.GetCharacter().Gender);
            foreach (var cloth in clothes)
            {
              if (cloth.SlotType == 1)
              {
                if (cloth.ClothId != -1)
                {
                  hats.Add(cloth.ClothId.ToString());
                }
                else
                {
                  hats.Add("Keinen");
                }
                continue;
              }
              switch (cloth.SlotId)
              {
                case 11:
                  tops.Add(cloth.ClothId.ToString());
                  break;
                case 4:
                  legs.Add(cloth.ClothId.ToString());
                  break;
                case 6:
                  shoes.Add(cloth.ClothId.ToString());
                  break;
              }
            }
          }
          player.TriggerEvent("showDutyClothMenu", hats.ToArray(), tops.ToArray(), legs.ToArray(), shoes.ToArray());
        }
      }

    }

    [RemoteEvent("keyPress:L")]
    public void KeyPressL(Player player)
    {
      if (!player.IsLoggedIn()) return;
      DoorManager.ChangeDoorState(player);
    }

    [RemoteEvent("keyPress:N")]
    public void KeyPressN(Player player)
    {
      if (!player.IsLoggedIn()) return;

      if (!player.IsInVehicle) return;
      if (player.VehicleSeat != 0) return;

      GTANetworkAPI.Vehicle v = player.Vehicle;

      User u = player.GetUser();
      if (u == null) return;

      if (NAPI.Entity.GetEntityVelocity(v).Length() > 1 && v.Class != 16)
      {
        player.SendNotification("~r~Der Motor kann nur im Stand betätigt werden.", true);
        return;
      }

      bool state = VehicleStreaming.GetEngineState(v);
      ServerVehicle sV = v.GetServerVehicle();
      if (sV != null)
      {
        if (sV is ShopVehicle)
        {
          VehicleStreaming.SetEngineState(v, false);
          return;
        }
        else if (sV is FactionVehicle fV)
        {
          if (fV.FactionId != u.FactionId && !state && !u.IsAdmin(AdminLevel.ADMIN3))
          {
            player.SendNotification("~r~Du hast keinen Schlüssel.");
            return;
          }
        }
        else if (sV is GroupVehicle gV)
        {
          if (gV.GroupId != u.Group.Id && !state && !u.IsAdmin(AdminLevel.ADMIN3))
          {
            player.SendNotification("~r~Du hast keinen Schlüssel.");
            return;
          }
        }
        else if (sV is JobVehicle jV)
        {
          if (!jV.GetJob().GetUsersInJob().Contains(player) && !u.IsAdmin(AdminLevel.ADMIN3))
          {
            player.SendNotification("~r~Du hast keinen Schlüssel.");
            return;
          }
        }
        else if (sV is UserVehicle uV)
        {
          if (uV.UserId != u.Id)
          {
            player.SendNotification("~r~Du hast keinen Schlüssel.");
            return;
          }
        }
        else if (sV is JobVehicle)
        {
          return;
        }
      }
      VehicleStreaming.SetEngineState(v, !state);
    }

    [RemoteEvent("keyPress:X")]
    public void KeyPressX(Player player)
    {
      if (!player.IsLoggedIn()) return;

      if (!player.IsInVehicle)
      {

        Vehicle.VehicleMenuLockCarEvent(player);

        GroundItem.PickUpGroundItem(player);
      }

      if (player.IsInVehicle && player.VehicleSeat == 0)
      {
        ServerVehicle veh = player.Vehicle.GetServerVehicle();
        if (veh != null)
        {
          if (veh is FactionVehicle fV && fV.FactionId != player.GetUser()?.FactionId && (!player.GetUser()?.IsAdmin(AdminLevel.ADMIN3) ?? false))
          {
            return;
          }
          else if (veh is ShopVehicle)
          {
            return;
          }
        }
        player.TriggerEvent("ToggleVehicleMenu");
      }
    }
  }
}
