using Xunit;
using QwirkleClassLibrary.Games;
using QwirkleClassLibrary.Persistences;
using System.IO;
using QwirkleClassLibrary.Players;

namespace TestBase
{
    public class TestPersistence
    {
        [Fact]
        public void Test_SaveGame()
        {
            var game = new Game();

            var gamePersistence = new GamePersistenceXml();
            gamePersistence.SaveGame(game);

            Assert.True(File.Exists("Game.xml"));
        }

        [Fact]
        public void Test_LoadGame()
        {
            Directory.SetCurrentDirectory("./../../../../Files");

            var game = new Game();

            game.AddPlayerInGame(["Jules", "Jérémy"]);
            game.StartGame();

            var gamePersistence = new GamePersistenceXml();
            gamePersistence.SaveGame(game);

            var loadedGame = gamePersistence.LoadGame();

            Assert.True(game.Board.ReadCells.All(cell =>
                cell.GetX == loadedGame.Board.GetCell(cell.GetX, cell.GetY)!.GetX &&
                cell.GetY == loadedGame.Board.GetCell(cell.GetX, cell.GetY)!.GetY &&
                cell.IsFree == loadedGame.Board.GetCell(cell.GetX, cell.GetY)!.IsFree));
        }

        [Fact]
        public void Test_SaveLeaderboard()
        {
            var leaderboard = new Leaderboard();

            var leaderboardPersistence = new LeaderboardPersistenceJson();
            leaderboardPersistence.SaveLeaderboard(leaderboard);

            Assert.True(File.Exists("Leaderboard.json"));
        }

        [Fact]
        public void Test_LoadLeaderboard()
        {
            var scoreboard = new Dictionary<string, int>()
            {
                { "Rémy", 60 },
                { "Jérémy", 50 },
                { "Jules", 100 }
            };

            var scoreboardro = scoreboard.AsReadOnly();

            var leaderboard = new Leaderboard();
            leaderboard.AddScoreInLead(scoreboardro);
            
            var leaderboardPersistence = new LeaderboardPersistenceJson();
            leaderboardPersistence.SaveLeaderboard(leaderboard);
            
            var loadedLeaderboard = leaderboardPersistence.LoadLeaderboard();

            Assert.Equal("Jules", loadedLeaderboard.Lb[0].PlayerName);
            Assert.Equal(100, loadedLeaderboard.Lb[0].Points);
            Assert.Equal(1, loadedLeaderboard.Lb[0].Victories);
        }
    }
}