using System.Runtime.Serialization.Json;
using QwirkleClassLibrary.Players;

namespace QwirkleClassLibrary.Persistences;

public class LeaderboardPersistenceJson : ILeaderboardPersistence
{
    public void SaveLeaderboard(Leaderboard leaderboard)
    {
        var serializer = new DataContractJsonSerializer(typeof(Leaderboard));
        
        using (Stream writer = File.Create("Leaderboard.json"))
        {
            serializer.WriteObject(writer, leaderboard);
        }
    }

    public Leaderboard LoadLeaderboard()
    {
        var serializer = new DataContractJsonSerializer(typeof(Leaderboard));

        using (Stream reader = File.OpenRead("Leaderboard.json"))
        {
            return serializer.ReadObject(reader) as Leaderboard ?? throw new InvalidOperationException();
        }
    }
}