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

public class PullItemIDs : MonoBehaviour
{
	public List<ItemData> itemList;

	public bool isstarted;

	public async void Start()
	{
		ConsoleScreen.Log("Fetching Item IDs");
		await FetchAndSaveDataAsync();
		ConsoleScreen.Log("Fetching Item IDs Completed");
		LoadItemData();
	}

	private async Task FetchAndSaveDataAsync()
	{
		var value = new { new
		{
			query = "query Items {\n                   items(lang: en) {\n                    id\n                    shortName\n                    name\n                    normalizedName\n                    types\n                    basePrice\n                    avg24hPrice\n                    }\n                   }"
		}.query };
		string text = Path.Combine(Application.persistentDataPath);
		Directory.CreateDirectory(text);
		string filePath = Path.Combine(text, "ItemIDs.Json");
		ConsoleScreen.Log("Fetching data from API.");
		using HttpClient httpClient = new HttpClient();
		_ = 1;
		try
		{
			StringContent content = new StringContent(JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json");
			ConsoleScreen.Log("Sending request");
			HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://api.tarkov.dev/graphql", content);
			if (!httpResponseMessage.IsSuccessStatusCode)
			{
				ConsoleScreen.LogError($"API request failed with status code: {httpResponseMessage.StatusCode}");
				return;
			}
			string value2 = await httpResponseMessage.Content.ReadAsStringAsync();
			ConsoleScreen.Log("Response received");
			dynamic val = JsonConvert.DeserializeObject<object>(value2);
			dynamic val2 = val.data.items.ToString();
			itemList = JsonConvert.DeserializeObject<List<ItemData>>(val2);
			string contents = JsonConvert.SerializeObject(itemList, Formatting.Indented);
			File.WriteAllText(filePath, contents);
			ConsoleScreen.Log("Response written to: " + filePath);
		}
		catch (Exception ex)
		{
			ConsoleScreen.LogError("An error occurred: " + ex.Message);
		}
	}

	private void LoadItemData()
	{
		try
		{
			string text = Path.Combine(Application.persistentDataPath, "ItemIDs.json");
			string text2 = Path.Combine(Application.persistentDataPath, "dev_items.json");
			ConsoleScreen.Log("Attempting to load item data from: " + text);
			if (File.Exists(text))
			{
				string value = File.ReadAllText(text);
				ConsoleScreen.Log("Successfully read JSON data from ItemIDs.json.");
				List<ItemData> list = JsonConvert.DeserializeObject<List<ItemData>>(value);
				if (list != null)
				{
					itemList = list;
					ConsoleScreen.Log($"Main item data loaded successfully. Items count: {itemList.Count}");
				}
				else
				{
					ConsoleScreen.Log("Error: Deserialized main item list is null.");
				}
			}
			else
			{
				ConsoleScreen.Log("Error: Main JSON file (ItemIDs.json) does not exist.");
			}
			ConsoleScreen.Log("Attempting to load dev item data from: " + text2);
			if (File.Exists(text2))
			{
				string value2 = File.ReadAllText(text2);
				ConsoleScreen.Log("Successfully read JSON data from dev_items.json.");
				List<ItemData> list2 = JsonConvert.DeserializeObject<List<ItemData>>(value2);
				if (list2 != null)
				{
					itemList.AddRange(list2);
					ConsoleScreen.Log($"Dev item data loaded successfully. Total items count: {itemList.Count}");
				}
				else
				{
					ConsoleScreen.Log("Error: Deserialized dev item list is null.");
				}
			}
			else
			{
				ConsoleScreen.Log("Error: Dev JSON file (dev_items.json) does not exist.");
			}
		}
		catch (Exception ex)
		{
			ConsoleScreen.Log("Error occurred while loading item data: " + ex.Message);
		}
	}
}
