using System;
using System.Collections.Generic;
using System.Linq;
using EFT.Interactive;
using EFT.InventoryLogic;
using stupid.solutions.stupid.solutions.Data;
using UnityEngine;

namespace stupid.solutions.Utils;

internal class GameCorpse
{
	private Vector3 _screenPosition;

	public Corpse Corpse { get; }

	public Vector3 ScreenPosition => _screenPosition;

	public bool IsOnScreen { get; private set; }

	public float Distance { get; private set; }

	public List<ContainerItem> LootItems { get; private set; }

	public bool ItemInit { get; private set; }

	public string FormattedDistance => $"{Math.Round(Distance)}m";

	public int? totalprice { get; private set; }

	public GameCorpse(Corpse corpse)
	{
		Corpse = corpse ?? throw new ArgumentNullException("corpse");
		_screenPosition = default(Vector3);
		Distance = 0f;
		LootItems = new List<ContainerItem>();
		ItemInit = false;
		totalprice = null;
	}

	public void RecalculateDynamics()
	{
		if (IsBodyValid(Corpse))
		{
			_screenPosition = GameUtils.WorldPointToScreenPoint(Corpse.transform.position);
			IsOnScreen = GameUtils.IsScreenPointVisible(_screenPosition);
			Distance = Vector3.Distance(Main.MainCamera.transform.position, Corpse.transform.position);
		}
	}

	public static bool IsBodyValid(Corpse corpse)
	{
		return corpse != null;
	}

	public void RefreshItems()
	{
		LootItems.Clear();
		foreach (Item allItem in Corpse.ItemOwner.RootItem.GetAllItems())
		{
			if (allItem == null)
			{
				continue;
			}
			ContainerItem lootItem = new ContainerItem(allItem);
			if (lootItem.Item.StackObjectsCount > lootItem.Item.StackMaxSize || 100 < lootItem.Item.StackObjectsCount || allItem.LocalizedName().ToString() == "Default Inventory")
			{
				continue;
			}
			lootItem.RecalculateDynamics();
			lootItem.SetItemCat();
			ContainerItem containerItem = LootItems.FirstOrDefault((ContainerItem i) => i.ItemID == lootItem.ItemID);
			if (containerItem != null)
			{
				containerItem.Count += lootItem.Count + (lootItem.Item.StackObjectsCount - 1);
				if (containerItem.Count > 1500)
				{
					containerItem.Count -= 1500;
				}
				if (containerItem.Count > 500)
				{
					containerItem.Count -= 500;
				}
			}
			else
			{
				if (lootItem.Item.StackObjectsCount > 1)
				{
					lootItem.Count += lootItem.Item.StackObjectsCount - 1;
				}
				LootItems.Add(lootItem);
			}
		}
		foreach (ContainerItem lootItem2 in LootItems)
		{
			lootItem2.CalculateItemPrice();
		}
		totalprice = LootItems.Sum((ContainerItem item) => item.itemprice);
		ItemInit = true;
	}
}
