using System.Text.Json;
using LittleTown.Core;
using LittleTown.Core.Ports;

namespace LittleTown.Blazor.Client.Services;

/// <summary>
/// Implementation du getter de données static pour WebAssembly via HttpClient
/// </summary>
public class WasmStaticDataGetter : IStaticDataGetter
{
    private readonly HttpClient _httpClient;
    private string _boardData = "";
    private string _buildingData = "";
    private string _objectivesData = "";
    private bool _isInitialized = false;

    public WasmStaticDataGetter(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    private async Task InitializeAsync()
    {
        if (_isInitialized) return;

        _boardData = await _httpClient.GetStringAsync("data/Board1.json");
        _buildingData = await _httpClient.GetStringAsync("data/Buildings.json");
        _objectivesData = await _httpClient.GetStringAsync("data/Objectives.json");

        _isInitialized = true;
    }

    /// <inheritdoc/>
    public async Task<Board> GetBoardAsync(int version)
    {
        // Synchronous wrapper - not ideal but matches interface
        await InitializeAsync();
        
        Board board = JsonSerializer.Deserialize<Board>(_boardData) 
            ?? throw new JsonException("Cannot deserialize Board");
        return board;
    }

    public Board GetBoard(int version)
    {
        throw new NotImplementedException("Use the asynchronous version of GetBoard for WebAssembly.");
    }

    /// <inheritdoc/>
    public ICollection<Building> GetBuildings()
    {
        InitializeAsync().GetAwaiter().GetResult();
        
        List<Building> buildings = JsonSerializer.Deserialize<List<Building>>(_buildingData) 
            ?? throw new JsonException("Cannot deserialize Buildings");
        return buildings;
    }

    /// <inheritdoc/>
    public ICollection<Objective> GetObjectives()
    {
        InitializeAsync().GetAwaiter().GetResult();
        
        List<Objective> objectives = JsonSerializer.Deserialize<List<Objective>>(_objectivesData) 
            ?? throw new JsonException("Cannot deserialize Objectives");
        return objectives;
    }
}
