namespace YatzyGame.Components
{
    public class MultiplayerController
    {
        public Dictionary<string, GameController> gameControllers = new Dictionary<string, GameController>();
        public Dictionary<string, string> playerGameControllerRelation = new Dictionary<string, string>();
        public Dictionary<string, string> JoinCodes = new Dictionary<string, string>();

        public string CreateGame(bool onlineMultiplayer, string name, string playerId)
        {
            var randomId = Guid.NewGuid().ToString();

            var joinCode = new Random().Next(1, 99999).ToString();

            gameControllers.Add(randomId, new GameController(randomId, onlineMultiplayer, joinCode));

            JoinCodes.Add(joinCode, randomId);

            GetGameController(randomId).AddPlayer(name, playerId, true);

            return randomId;
        }

        public GameController GetGameController(string id)
        {
            if (gameControllers.ContainsKey(id))
            {
                return gameControllers[id];
            }

            return null;
        }

        public GameController GetPlayerGameController(string id)
        {
            if (playerGameControllerRelation.ContainsKey(id))
            {
                return GetGameController(playerGameControllerRelation[id]);
            }

            return null;
        }

        public GameController GetGameControllerFromJoinCode(string joinCode)
        {
            var gameId = JoinCodes.Where(x => x.Key.Equals(joinCode)).First().Value;
            var gameController = GetGameController(gameId);

            if (gameController != null)
            {
                return gameController;
            }

            return null;
        }

        public void CreatePlayer(string gameID, string playerId, string name)
        {
            var controller = GetGameController(gameID);

            controller.AddPlayer(name, playerId);

            playerGameControllerRelation.Add(playerId, gameID);
        }
    }
}