using System.Text.Json;

namespace IS_Lab2_JSON_CS;

public class DeserializeJson
{
    public JsonDocument Data { get; set; }

    public DeserializeJson(string filename)
    {
        var text = File.ReadAllText(filename);
        Data = JsonDocument.Parse(text);
    }

    public void SomeStats()
    {
        var exampleStat = 0;
        var voivodeships = new Dictionary<string, Dictionary<string, int>>();

        foreach (var obj in Data.RootElement.EnumerateArray())
        {
            var voivodeshipName = obj.GetProperty("Województwo")
                .GetString()!;

            var jstType = obj.GetProperty("typ_JST")
                .GetString()!;

            if (!voivodeships.TryGetValue(voivodeshipName, out var voivodeshipDict))
            {
                voivodeshipDict = new Dictionary<string, int>();
                voivodeships[voivodeshipName] = voivodeshipDict;
            }

            voivodeshipDict.TryGetValue(jstType, out var amount);
            voivodeshipDict[jstType] = amount + 1;

            if (jstType == "GM" &&
                voivodeshipName.Equals("dolnośląskie", StringComparison.InvariantCultureIgnoreCase))
            {
                exampleStat += 1;
            }
        }
        
        Console.WriteLine($"Liczba urzędów miejskich w województwie dolnośląskim: {exampleStat}");
        foreach (var voivodeshipPair in voivodeships)
        {
            Console.WriteLine($"Województwo {voivodeshipPair.Key}: ");
            foreach (var typePair in voivodeshipPair.Value)
            {
                Console.WriteLine($"\t- {typePair.Key}: {typePair.Value}");
            }
        }
    }
}