Exemplo n.º 1
0
        public static async Task <int[]> CreateLevels(this InWordsDataContext context, int gameId, int userId, IList <int[]> pairsInLevels)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (pairsInLevels == null)
            {
                pairsInLevels = Array.Empty <int[]>();
            }

            // create levles
            var levels = pairsInLevels.Select(d =>
            {
                var game = new GameLevel()
                {
                    GameId = gameId
                };
                game.Historylevel = new Historylevel()
                {
                    DateTime   = DateTime.UtcNow,
                    WordsCount = d.Distinct().Count(),
                    GameLevel  = game
                };
                context.Add(game);
                return(game);
            }).ToArray();

            await context.SaveChangesAsync().ConfigureAwait(false);

            // fill levels with words
            for (int i = 0; i < pairsInLevels.Count; i++)
            {
                var   currentLevel    = levels[i];
                int[] currentWordsIds = pairsInLevels[i].ToArray();

                var currentWords = context.CurrentUserWordPairs(userId)
                                   .Where(u => currentWordsIds.Contains(u.UserWordPairId))
                                   .ToArray();

                var gameLevelWords = currentWords.Select(w => new GameLevelWord()
                {
                    ForeignWord = w.ForeignWord,
                    NativeWord  = w.NativeWord,
                    GameLevelId = currentLevel.GameLevelId,
                }).ToArray();

                context.GameLevelWords.AddRange(gameLevelWords);
            }
            await context.SaveChangesAsync().ConfigureAwait(false);

            return(levels.Select(level => level.GameLevelId).ToArray());
        }