using System;
using System.Collections.Generic;
using System.Reflection;
using Comfort.Common;
using EFT.InventoryLogic;

public class PresetFactory
{
	private static Type _presetFactoryType;

	private static FieldInfo _itemPresetsField;

	private static object _presetFactoryInstance;

	static PresetFactory()
	{
		LoadPresetFactoryType();
	}

	private static void LoadPresetFactoryType()
	{
		Assembly assembly = Assembly.Load("Assembly-CSharp");
		if (assembly == null)
		{
			ItemFactory.Log("Log: Failed to load Assembly-CSharp.");
			return;
		}
		Type[] types = assembly.GetTypes();
		foreach (Type type in types)
		{
			if (type.Name == "\uef57")
			{
				_presetFactoryType = type;
				break;
			}
		}
		if (_presetFactoryType == null)
		{
			ItemFactory.Log("Log: Failed to find PresetFactory type.");
			return;
		}
		ItemFactory.Log("Log: Found PresetFactory type: " + _presetFactoryType.FullName);
		PropertyInfo property = typeof(Singleton<>).MakeGenericType(_presetFactoryType).GetProperty("Instance", BindingFlags.Static | BindingFlags.Public);
		if (property != null)
		{
			_presetFactoryInstance = property.GetValue(null);
		}
		_itemPresetsField = _presetFactoryType.GetField("ItemPresets", BindingFlags.Instance | BindingFlags.NonPublic);
		if (_itemPresetsField == null)
		{
			ItemFactory.Log("Log: Failed to find ItemPresets field.");
		}
	}

	public static Dictionary<string, object> GetItemPresets()
	{
		if (_presetFactoryInstance == null || _itemPresetsField == null)
		{
			ItemFactory.Log("Log: PresetFactory is not properly initialized.");
			return null;
		}
		Dictionary<string, object> dictionary = _itemPresetsField.GetValue(_presetFactoryInstance) as Dictionary<string, object>;
		if (dictionary != null)
		{
			ItemFactory.Log($"Log: Found {dictionary.Count} item presets.");
		}
		else
		{
			ItemFactory.Log("Log: ItemPresets is null.");
		}
		return dictionary;
	}

	public static Item SpawnPresetItem(string templateId)
	{
		Dictionary<string, object> itemPresets = GetItemPresets();
		if (itemPresets == null || !itemPresets.ContainsKey(templateId))
		{
			ItemFactory.Log("Log: No preset found for the given templateId.");
			return null;
		}
		object obj = itemPresets[templateId];
		PropertyInfo property = obj.GetType().GetProperty("Item", BindingFlags.Instance | BindingFlags.Public);
		if (property != null)
		{
			Item result = property.GetValue(obj) as Item;
			ItemFactory.Log("Log: Spawned preset item with templateId: " + templateId);
			return result;
		}
		ItemFactory.Log("Log: Failed to retrieve Item from the preset.");
		return null;
	}
}
