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

public class PullQuestIDs : MonoBehaviour
{
	private async void Start()
	{
		ConsoleScreen.Log("Fetching Quest IDs");
		await FetchAndSaveDataAsync();
		ConsoleScreen.Log("Fetching Quest IDs Completed");
	}

	private async Task FetchAndSaveDataAsync()
	{
		var value = new { new
		{
			query = "query Tasks \n                    {\n                      tasks(lang: en, gameMode: pve) \n                       {\n                        trader {\n                                name\n                               }\n                        name\n                        id\n                        experience\n                        factionName\n                        kappaRequired\n                        lightkeeperRequired\n                        minPlayerLevel\n                        objectives {\n                                    type\n                                    description\n                                    }\n                        restartable\n                        }\n                    }"
		}.query };
		string text = Path.Combine(Application.persistentDataPath);
		Directory.CreateDirectory(text);
		string filePath = Path.Combine(text, "QuestIDs.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 contents = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(await httpResponseMessage.Content.ReadAsStringAsync()), Formatting.Indented);
			File.WriteAllText(filePath, contents);
			ConsoleScreen.Log("Response written to: " + filePath);
		}
		catch (Exception ex)
		{
			ConsoleScreen.LogError("An error occurred: " + ex.Message);
		}
	}
}
