using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using EFT.UI;
using Newtonsoft.Json;
using UnityEngine;

namespace stupid.solutions;

public class PullItemPresets : MonoBehaviour
{
	public List<TemplateData> templateList;

	public async void Start()
	{
		ConsoleScreen.Log("Fetching Item Presets");
		await LoadPresetsData();
		ConsoleScreen.Log("Item Presets Loaded");
	}

	private async Task LoadPresetsData()
	{
		string filePath = Path.Combine(Application.persistentDataPath, "itempresetslist.json");
		if (File.Exists(filePath))
		{
			try
			{
				Dictionary<string, List<TemplateData>> dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<TemplateData>>>(await Task.Run(() => File.ReadAllText(filePath)));
				if (dictionary != null && dictionary.ContainsKey("Templates"))
				{
					templateList = dictionary["Templates"];
					ConsoleScreen.Log($"Item presets loaded successfully. Template count: {templateList.Count}");
				}
				else
				{
					ConsoleScreen.LogError("Error: Deserialized template list is null or malformed.");
				}
				return;
			}
			catch (Exception ex)
			{
				ConsoleScreen.LogError("Error occurred while loading item presets: " + ex.Message);
				return;
			}
		}
		ConsoleScreen.LogError("Error: JSON file (" + filePath + ") does not exist.");
	}

	public void SaveItemToPresetList(dynamic item, string presetName)
	{
		Dictionary<string, SlotData> dictionary = new Dictionary<string, SlotData>();
		foreach (dynamic item3 in item.AllSlots)
		{
			if (item3.ContainedItem != null)
			{
				dictionary[item3.FullId] = new SlotData
				{
					SlotID = item3.FullId,
					SlotName = item3.Name,
					ItemId = item3.ContainedItem.TemplateId
				};
			}
		}
		TemplateData templateData = new TemplateData();
		templateData.PresetName = presetName;
		Dictionary<string, ItemTemplate> dictionary2 = new Dictionary<string, ItemTemplate>();
		dictionary2.Add(item.TemplateId.ToString(), new ItemTemplate
		{
			StackMaxSize = 1,
			QuestItem = false,
			Description = $"Saved on {DateTime.Now}, Made With Advanced Item Spawner",
			Slots = dictionary
		});
		templateData.ItemTemplate = dictionary2;
		TemplateData item2 = templateData;
		string path = Path.Combine(Application.persistentDataPath, "itempresetslist.json");
		Dictionary<string, List<TemplateData>> dictionary3 = ((!File.Exists(path)) ? new Dictionary<string, List<TemplateData>>() : (JsonConvert.DeserializeObject<Dictionary<string, List<TemplateData>>>(File.ReadAllText(path)) ?? new Dictionary<string, List<TemplateData>>()));
		if (!dictionary3.ContainsKey("Templates"))
		{
			dictionary3["Templates"] = new List<TemplateData>();
		}
		dictionary3["Templates"].Add(item2);
		File.WriteAllText(path, JsonConvert.SerializeObject(dictionary3, Formatting.Indented));
		ConsoleScreen.Log("Preset saved to list.");
		Start();
	}
}
