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

namespace LittleTown.StaticDataAcces;

/// <summary>
/// Implementation du getter de données static en fichier local
/// </summary>
public class StaticDataGetter : IStaticDataGetter
{
    string _boardData = "";
    string _buildingData = "";
    string _objectivesData = "";

    /// <summary>
    /// Constructeur avec les chemin des fichiers de données
    /// </summary>
    /// <param name="boardData">structure json definissant le plateau</param>
    /// <param name="buildingData">structure json definissant les building</param>
    /// <param name="objectivesData">structure json definissant les objectifs</param>
    public StaticDataGetter(string boardData, string buildingData, string objectivesData)
    {
        _boardData = boardData;
        _objectivesData = objectivesData;
        _buildingData = buildingData;
    }

    /// <summary> Constructeur avec les chemins par défaut </summary>
    public StaticDataGetter()
    {
        // Les fichiers JSON sont copiés dans le dossier de build via le .csproj
        // Ils sont donc toujours relatifs à l'exécutable
        var baseDirectory = AppContext.BaseDirectory;
        string boardPath = Path.Combine(baseDirectory, "Data", "Board1.json");
        string buildingPath = Path.Combine(baseDirectory, "Data", "Buildings.json");
        string objectivesPath = Path.Combine(baseDirectory, "Data", "Objectives.json");

        ReadFiles(boardPath, buildingPath, objectivesPath);
    }

    private void ReadFiles(string boardPath, string buildingPath, string objectivesPath)
    {
        _boardData = File.ReadAllText(boardPath);
        _buildingData = File.ReadAllText(buildingPath);
        _objectivesData = File.ReadAllText(objectivesPath);
    }

    /// <inheritdoc/>
    public Board GetBoard(int version)
    {
        Board board = JsonSerializer.Deserialize<Board>(_boardData) ?? throw new JsonException("Cannot deserialize Board");
        return board;
    }

    public Task<Board> GetBoardAsync(int version)
    {
        return Task.FromResult(GetBoard(version));
    }

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

        return buildings;
    }

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

        return objectives;
    }
}