using System.Runtime.Serialization;
using QwirkleClassLibrary.Games;

namespace QwirkleClassLibrary.Persistences;

public class GamePersistenceXml : IGamePersistence
{
    public void SaveGame(Game game)
    {
        var serializer = new DataContractSerializer(typeof(Game),
            new DataContractSerializerSettings() { PreserveObjectReferences = true });
        
        using (Stream writer = File.Create("Game.xml"))
        {
            serializer.WriteObject(writer, game);
        }
    }

    public Game LoadGame()
    {
        var serializer = new DataContractSerializer(typeof(Game));

        try
        {
            using (Stream reader = File.OpenRead("Game.xml"))
            {
                var newGame = serializer.ReadObject(reader) as Game;
                return newGame!;
            }
        }
        catch
        {
            return new Game();
        }
    }
}