using DumpCleaner;
using QuestValidator.Common;
using QuestValidator.Common.Helpers;
using System.Text.Json;
using System.Text.Json.Nodes;

public class LocationData
{
    public LocationData(Location location, Dump rawLocation)
    {
        Location = location;
        RawLocation = rawLocation;
    }
    public Location Location { get; set; }
    public Dump RawLocation { get; set; }
}

public class LocationParser
{
    private readonly Dictionary<string, LocationData> locations = new Dictionary<string, LocationData>();
    private readonly string outputPath;

    public LocationParser(string outputPath)
    {
        this.outputPath = outputPath;
    }

    internal void AddLocalLootDump(Dump dumpFile, string rawJson)
    {
        var locationData = JsonSerializer.Deserialize<Location>(dumpFile.data.ToString());
        var locationName = locationData.Id;

        // already parsed, skip
        if (locations.ContainsKey(locationName))
        {
            return;
        }

        // remove loot as not needed for base.json
        locationData.Loot?.Clear();

        // remove loot from raw file
        JsonNode? parsedJson = JsonNode.Parse(rawJson);

        var data = parsedJson["data"];
        data["Loot"] = new JsonArray();

        var lootFreeJson = parsedJson.ToString();

        locations.Add(locationName, new LocationData(locationData, JsonSerializer.Deserialize<Dump>(lootFreeJson)));
    }

    internal void CreateLocationFile()
    {
        foreach (var location in locations)
        {

            if (string.Equals(location.Value.Location.Id, "lighthouse2", StringComparison.CurrentCultureIgnoreCase))
            {
                continue;
            }

            JsonWriter.WriteJson(location.Value.RawLocation.data, $"{outputPath}/{location.Value.Location.Id.ToLower()}", Directory.GetCurrentDirectory(), "base");
            LoggingHelpers.LogToConsole($"Found map file: {location.Value.Location.Id} wrote file to output folder");
        }
    }
}