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, à utiliser pour les tests seulement </summary>
    public StaticDataGetter()
    {
        string boardPath = Path.Combine(Environment.CurrentDirectory, "../../../../LittleTown.StaticDataAccess/Data/Board1.json");
        string buildingPath = Path.Combine(Environment.CurrentDirectory, "../../../../LittleTown.StaticDataAccess/Data/Buildings.json");
        string objectivesPath = Path.Combine(Environment.CurrentDirectory, "../../../../LittleTown.StaticDataAccess/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;
    }

    /// <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;
    }
}