using System.Collections.Generic;
using System.Linq;
using GTANetworkAPI;
using ReallifeGamemode.Database.Entities;
using ReallifeGamemode.Database.Models;
using ReallifeGamemode.Server.Extensions;
using ReallifeGamemode.Server.Inventory.Interfaces;
using ReallifeGamemode.Server.Managers;
using ReallifeGamemode.Server.Util;
using Newtonsoft.Json;
using ReallifeGamemode.Server.Types;

namespace ReallifeGamemode.Server.Events
{
  public class Inventory : Script
  {
    [RemoteEvent("getNearVehicles")]
    public void SrvEvent_GetNearVehicles(Player client)
    {
      var user = client.GetUser();
      if (!client.IsInVehicle)
      {
        using (var context = new DatabaseContext())
        {
          foreach (GTANetworkAPI.Vehicle veh in NAPI.Pools.GetAllVehicles())
          {
            List<VehicleInventory> vehicleInventory = new List<VehicleInventory>();
            if (veh.Position.DistanceTo(client.Position) < 5f)
            {
              if (VehicleStreaming.GetDoorState(veh, DoorID.DoorTrunk) == DoorState.DoorOpen || VehicleStreaming.GetDoorState(veh, DoorID.DoorRearLeft) == DoorState.DoorOpen || VehicleStreaming.GetDoorState(veh, DoorID.DoorRearRight) == DoorState.DoorOpen)
              {
                vehicleInventory = getVehItem(veh);
              }
              client.TriggerEvent("setVehiclesInventory", vehicleInventory.ToArray());
              return;
            }
          }
        }
      }
    }

    public List<VehicleInventory> getVehItem(GTANetworkAPI.Vehicle veh)
    {
      List<string> iName = new List<string>();
      List<int> iAmount = new List<int>();
      List<int> iId = new List<int>();
      List<VehicleInventory> vehicleInventory = new List<VehicleInventory>();
      var inventoryWeight = 0;
      using (var context = new DatabaseContext())
      {
        ServerVehicle serverVehicle = VehicleManager.GetServerVehicleFromVehicle(veh, context);
        List<VehicleItem> vehicleItems = context.VehicleItems.ToList().FindAll(i => i.VehicleId == serverVehicle.Id);
        foreach (var vehItem in vehicleItems)
        {
          IItem iItem = InventoryManager.GetItemById(vehItem.ItemId);
          var currentItemWeight = iItem.Gewicht * vehItem.Amount;
          inventoryWeight += currentItemWeight;

          iName.Add(iItem.Name);
          iAmount.Add(vehItem.Amount);
          iId.Add(iItem.Id);
        }
        var vehInv = new VehicleInventory
        {
          ID = serverVehicle.Id,
          currentWeight = inventoryWeight,
          totalWeight = 250,
          ivehName = iName.ToArray(),
          ivehAmount = iAmount.ToArray(),
          ivehId = iId.ToArray()
        };
        vehicleInventory.Add(vehInv);
      }
      return vehicleInventory;
    }
  }
}
