public async Task <ActionResult> Create([Bind(Include = "TeamId,Name,City")] Team team)
        {
            if (ModelState.IsValid)
            {
                db.Teams.Add(team);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(team));
        }
        public async Task <ActionResult> Create([Bind(Include = "PlayerId,JerseyNumber,FirstName,LastName,Position,Country,TeamId")] Player player)
        {
            if (ModelState.IsValid)
            {
                db.Players.Add(player);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            ViewBag.TeamId = new SelectList(db.Teams, "TeamId", "Name", player.TeamId);
            return(View(player));
        }
        public async Task Post()
        {
            var user = await _userManager.GetUserAsync(User);

            string[]          favs       = Request.Form["fav"];
            string[]          nonFavs    = Request.Form["nonFav"];
            List <Favourites> favourites = new List <Favourites>();

            foreach (var fav in favs)
            {
                //prevent duplicates
                var currentFavourites = _context.Favourites.Where(x => x.PlayerId == int.Parse(fav) && x.UserId == user.Id);
                if (!currentFavourites.Any())
                {
                    favourites.Add(new Favourites
                    {
                        PlayerId = int.Parse(fav),
                        UserId   = user.Id
                    });
                }
            }

            foreach (var nonfav in nonFavs)
            {
                var deFavs = _context.Favourites.Where(x => x.PlayerId == int.Parse(nonfav) && x.UserId == user.Id);

                if (deFavs.Any())
                {
                    _context.Favourites.RemoveRange(deFavs.ToList());
                }
            }

            await _context.Favourites.AddRangeAsync(favourites);

            await _context.SaveChangesAsync();
        }
        public async Task <string> CreateSeason(string name, string abbreviation, string[] players, string[] pacific, string[] central, string[] atlantic, string[] metropolitan)
        {
            if (name == null)
            {
                return("Please enter a team name!");
            }

            if (abbreviation == null || abbreviation.Length != 3)
            {
                return("abbreviation must be 3 characters!");
            }

            abbreviation = abbreviation.ToUpper();

            var hMPlayers = await _context.Players.Include(x => x.PlayerInfo).Where(x => players.Contains(x.PlayerInfoId.ToString()) && x.ApiId != 0).ToListAsync();

            var forwards   = 0;
            var defencemen = 0;
            var goalies    = 0;

            foreach (var player in hMPlayers)
            {
                //Count every position
                if (player.Position == "C" || player.Position == "LW" || player.Position == "RW")
                {
                    forwards++;
                }
                else if (player.Position == "D")
                {
                    defencemen++;
                }
                else if (player.Position == "G")
                {
                    goalies++;
                }

                //Check to make sure the user hasn't exceeded the player position limit
                if (forwards > 12)
                {
                    return("Too many forwards!");
                }
                else if (defencemen > 6)
                {
                    return("Too many defencemen!");
                }
                else if (goalies > 2)
                {
                    return("Too many goalies!");
                }
            }
            //Check if team is too big or too small
            if ((forwards + defencemen + goalies) > 20)
            {
                return("Too many players!");
            }
            else if ((forwards + defencemen + goalies) < 20)
            {
                return($"{20 - (forwards + defencemen + goalies)} more players are required.");
            }

            //All validation succeeded

            //Create users team and players
            var      season    = new Season();
            DateTime startDate = new DateTime(DateTime.Now.Year, 10, 15);

            season.Date   = startDate;
            season.UserId = _userManager.GetUserId(User);

            await _context.Seasons.AddAsync(season);

            await _context.SaveChangesAsync();

            HMTeamInfo teamInfo = new HMTeamInfo();

            teamInfo.Name         = name;
            teamInfo.Abbreviation = abbreviation;

            await _context.TeamInfo.AddAsync(teamInfo);

            await _context.SaveChangesAsync();


            HMTeam myTeam = new HMTeam();

            myTeam.TeamInfoId = teamInfo.Id;
            myTeam.SeasonId   = season.Id;
            myTeam.UserId     = _userManager.GetUserId(User);

            var inPacific  = pacific.Contains("myTeam");
            var inCentral  = central.Contains("myTeam");
            var inAtlantic = atlantic.Contains("myTeam");
            var inMetro    = metropolitan.Contains("myTeam");

            if (inPacific)
            {
                myTeam.Division   = "Pacific";
                myTeam.Conference = "Western";
            }
            else if (inCentral)
            {
                myTeam.Division   = "Central";
                myTeam.Conference = "Western";
            }
            else if (inAtlantic)
            {
                myTeam.Division   = "Atlantic";
                myTeam.Conference = "Eastern";
            }
            else if (inMetro)
            {
                myTeam.Division   = "Metropolitan";
                myTeam.Conference = "Eastern";
            }

            await _context.Teams.AddAsync(myTeam);

            await _context.SaveChangesAsync();

            List <HMPlayer> newlyGeneratedRoster = new List <HMPlayer>();

            foreach (var player in hMPlayers)
            {
                newlyGeneratedRoster.Add(new HMPlayer
                {
                    Position     = player.Position,
                    Overall      = player.Overall,
                    TeamId       = myTeam.Id,
                    PlayerInfoId = player.PlayerInfoId
                });
            }

            await _context.Players.AddRangeAsync(newlyGeneratedRoster);

            await _context.SaveChangesAsync();

            //Create league teams and players

            var           leagueTeams         = _context.Teams.Include(x => x.TeamInfo).Where(x => x.ApiId != 0).ToList();
            List <HMTeam> newlyGeneratedTeams = new List <HMTeam>();

            foreach (var team in leagueTeams)
            {
                var teamInPacific  = pacific.Contains(team.TeamInfoId.ToString());
                var teamInCentral  = central.Contains(team.TeamInfoId.ToString());
                var teamInAtlantic = atlantic.Contains(team.TeamInfoId.ToString());
                var teamInMetro    = metropolitan.Contains(team.TeamInfoId.ToString());

                string division   = "N/A";
                string conference = "N/A";

                if (teamInPacific)
                {
                    division   = "Pacific";
                    conference = "Western";
                }
                else if (teamInCentral)
                {
                    division   = "Central";
                    conference = "Western";
                }
                else if (teamInAtlantic)
                {
                    division   = "Atlantic";
                    conference = "Eastern";
                }
                else if (teamInMetro)
                {
                    division   = "Metropolitan";
                    conference = "Eastern";
                }

                newlyGeneratedTeams.Add(new HMTeam
                {
                    Division   = division,
                    Conference = conference,
                    TeamInfoId = team.TeamInfoId,
                    SeasonId   = season.Id
                });
            }

            await _context.Teams.AddRangeAsync(newlyGeneratedTeams);

            await _context.SaveChangesAsync();


            List <HMPlayer> newGeneratedPlayers = new List <HMPlayer>();
            var             leaguePlayers       = _context.Players.Include(x => x.Team.TeamInfo).Where(x => x.ApiId != 0);

            foreach (var team in newlyGeneratedTeams)
            {
                var teamPlayers = leaguePlayers.Where(x => x.Team.TeamInfoId == team.TeamInfoId).ToList();

                foreach (var player in teamPlayers)
                {
                    newGeneratedPlayers.Add(new HMPlayer
                    {
                        Position     = player.Position,
                        Overall      = player.Overall,
                        TeamId       = team.Id,
                        PlayerInfoId = player.PlayerInfoId
                    });
                }
            }

            await _context.Players.AddRangeAsync(newGeneratedPlayers);

            await _context.SaveChangesAsync();

            //Create Schedule

            List <Game>   games    = new List <Game>();
            List <HMTeam> allTeams = new List <HMTeam>();

            allTeams.AddRange(newlyGeneratedTeams);
            allTeams.Add(myTeam);



            if (allTeams.Count % 2 != 0)
            {
                allTeams.Add(new HMTeam
                {
                    TeamInfo = new HMTeamInfo {
                        Name = "Bye"
                    }
                });
            }

            int numDays  = (allTeams.Count - 1);
            int halfSize = allTeams.Count / 2;

            List <HMTeam> teams = new List <HMTeam>();

            teams.AddRange(allTeams.Skip(halfSize).Take(halfSize));
            teams.AddRange(allTeams.Skip(1).Take(halfSize - 1).ToArray().Reverse());

            int teamsSize = teams.Count;

            for (int day = 0; day < numDays; day++)
            {
                int teamIdx = day % teamsSize;

                games.Add(new Game
                {
                    Date       = startDate.AddDays(day),
                    Complete   = false,
                    AwayTeamId = teams[teamIdx].Id,
                    HomeTeamId = allTeams[0].Id
                });

                for (int idx = 1; idx < halfSize; idx++)
                {
                    int firstTeam  = (day + idx) % teamsSize;
                    int secondTeam = (day + teamsSize - idx) % teamsSize;
                    games.Add(new Game
                    {
                        Date       = startDate.AddDays(day),
                        Complete   = false,
                        AwayTeamId = teams[firstTeam].Id,
                        HomeTeamId = teams[secondTeam].Id
                    });
                }
            }

            await _context.Games.AddRangeAsync(games);

            await _context.SaveChangesAsync();

            return(season.Id.ToString());
        }
        public async Task FetchApiData()
        {
            var anyTeams = _context.TeamInfo.Any();

            if (anyTeams)
            {
                return;
            }

            var TeamUrl    = "https://statsapi.web.nhl.com/api/v1/teams";
            var httpClient = HttpClientFactory.Create();
            var teamData   = await httpClient.GetStringAsync(TeamUrl);

            var teams = JsonConvert.DeserializeObject <TeamRoot>(teamData);

            List <HMTeam> hMTeams = new List <HMTeam>();

            foreach (var team in teams.teams)
            {
                HMTeamInfo hMTeamsInfo = new HMTeamInfo();
                HMTeam     hMTeam      = new HMTeam();

                var teamStatsUrl  = $"https://statsapi.web.nhl.com/api/v1/teams/{team.id}/stats";
                var teamStatsData = await httpClient.GetStringAsync(teamStatsUrl);

                var teamStats = JsonConvert.DeserializeObject <TeamStatRoot>(teamStatsData);

                hMTeamsInfo.Name         = team.name;
                hMTeamsInfo.Abbreviation = team.abbreviation;
                hMTeamsInfo.logoUrl      = $"https://www-league.nhlstatic.com/images/logos/teams-current-primary-light/{team.id}.svg";

                await _context.TeamInfo.AddAsync(hMTeamsInfo);

                await _context.SaveChangesAsync();

                try
                {
                    hMTeams.Add(new HMTeam
                    {
                        Division      = team.division.name,
                        Conference    = team.conference.name,
                        GamesPlayed   = teamStats.stats[0].splits[0].stat.gamesPlayed,
                        Wins          = Convert.ToInt32(teamStats.stats[0].splits[0].stat.wins),
                        Loses         = Convert.ToInt32(teamStats.stats[0].splits[0].stat.losses),
                        OvertimeLoses = Convert.ToInt32(teamStats.stats[0].splits[0].stat.ot),
                        Points        = Convert.ToInt32(teamStats.stats[0].splits[0].stat.pts),
                        ApiId         = team.id,
                        TeamInfoId    = hMTeamsInfo.Id
                    });
                } catch (Exception)
                {
                    hMTeams.Add(new HMTeam
                    {
                        Division      = team.division.name,
                        Conference    = team.conference.name,
                        GamesPlayed   = 0,
                        Wins          = 0,
                        Loses         = 0,
                        OvertimeLoses = 0,
                        Points        = 0,
                        ApiId         = team.id,
                        TeamInfoId    = hMTeamsInfo.Id
                    });
                }
            }

            await _context.Teams.AddRangeAsync(hMTeams);

            await _context.SaveChangesAsync();

            //Fetch Players

            List <HMPlayer> hMPlayers = new List <HMPlayer>();

            foreach (var team in hMTeams)
            {
                var rosterUrl  = $"https://statsapi.web.nhl.com/api/v1/teams/{team.ApiId}/roster";
                var rosterData = await httpClient.GetStringAsync(rosterUrl);

                var roster = JsonConvert.DeserializeObject <PersonRoot>(rosterData);

                foreach (var player in roster.roster)
                {
                    HMPlayerInfo hMPlayerInfo = new HMPlayerInfo();
                    try
                    {
                        var playerUrl  = $"https://statsapi.web.nhl.com/api/v1/people/{player.person.id}";
                        var playerData = await httpClient.GetStringAsync(playerUrl);

                        var playerAbout = JsonConvert.DeserializeObject <PeopleRoot>(playerData);

                        var playerStatsUrl  = $"https://statsapi.web.nhl.com/api/v1/people/{player.person.id}/stats?stats=statsSingleSeason&season=20202021";
                        var playerStatsData = await httpClient.GetStringAsync(playerStatsUrl);

                        var playerStats = JsonConvert.DeserializeObject <StatsRoot>(playerStatsData);


                        hMPlayerInfo.Name        = player.person.fullName;
                        hMPlayerInfo.Country     = playerAbout.People[0].BirthCountry;
                        hMPlayerInfo.DateOfBirth = playerAbout.People[0].BirthDate;
                        hMPlayerInfo.Height      = playerAbout.People[0].Height;
                        hMPlayerInfo.Weight      = playerAbout.People[0].Weight;
                        hMPlayerInfo.HeadShotUrl = $"https://nhl.bamcontent.com/images/headshots/current/168x168/{player.person.id}.jpg";

                        await _context.PlayerInfo.AddAsync(hMPlayerInfo);

                        await _context.SaveChangesAsync();

                        var TOI = playerStats.stats[0].splits[0].stat.timeOnIce.Split(":");
                        int.TryParse(TOI[0], out int parsedTOI);

                        hMPlayers.Add(new HMPlayer
                        {
                            Position        = player.position.abbreviation,
                            GamesPlayed     = playerStats.stats[0].splits[0].stat.games,
                            TimeOnIce       = parsedTOI,
                            Shots           = playerStats.stats[0].splits[0].stat.shots,
                            Goals           = playerStats.stats[0].splits[0].stat.goals,
                            Assists         = playerStats.stats[0].splits[0].stat.assists,
                            Points          = playerStats.stats[0].splits[0].stat.points,
                            Hits            = playerStats.stats[0].splits[0].stat.hits,
                            PowerPlayGoals  = playerStats.stats[0].splits[0].stat.powerPlayGoals,
                            PenalityMinutes = playerStats.stats[0].splits[0].stat.pim,
                            Saves           = playerStats.stats[0].splits[0].stat.saves,
                            Shutouts        = playerStats.stats[0].splits[0].stat.shutouts,
                            GoalsAgainst    = playerStats.stats[0].splits[0].stat.goalsAgainst,
                            PlusMinus       = playerStats.stats[0].splits[0].stat.plusMinus,
                            ApiId           = player.person.id,
                            TeamId          = team.Id,
                            PlayerInfoId    = hMPlayerInfo.Id
                        });
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        string test = ex.Message;
                    }
                }
            }

            await _context.Players.AddRangeAsync(hMPlayers);

            await _context.SaveChangesAsync();

            //Populate Pool rulesets

            List <RuleSet> ruleSets = new List <RuleSet>();

            ruleSets.Add(new RuleSet
            {
                Name          = "Top Scorers",
                Description   = "Do you believe that you have what it takes to pick the top goal scorers in the league? Pick your top 5 skaters from any team.",
                maxForwards   = 5,
                maxDefensemen = 5,
                maxGoalies    = 0,
                maxPlayers    = 5
            });

            ruleSets.Add(new RuleSet
            {
                Name          = "Point Producers",
                Description   = "Pick your top point producers from around the league. Pick 7 forwards and 3 defenceman.",
                maxForwards   = 7,
                maxDefensemen = 3,
                maxGoalies    = 0,
                maxPlayers    = 10
            });

            ruleSets.Add(new RuleSet
            {
                Name          = "Assist Machine",
                Description   = "Nothing but assists! Pick your top 5 assist getters.",
                maxForwards   = 5,
                maxDefensemen = 5,
                maxGoalies    = 0,
                maxPlayers    = 5
            });

            await _context.RuleSets.AddRangeAsync(ruleSets);

            await _context.SaveChangesAsync();
        }
        public async Task <string> AddOrUpdateTeam(int id, string name, string[] players)
        {
            var anyTeam = _context.Teams.Include(x => x.TeamInfo).Where(x => x.PoolId == id && x.UserId == _userManager.GetUserId(User));

            var enrolledPool = _context.PoolList.Where(x => x.PoolId == id && _userManager.GetUserId(User) == x.UserId).FirstOrDefault();

            if (enrolledPool == null)
            {
                return("You're not enrolled in this pool!!");
            }

            if (name == null)
            {
                return("Please enter a team name.");
            }

            var ruleId = _context.Pools.Where(x => x.Id == id).FirstOrDefault().RuleSetId;

            if (ruleId == null)
            {
                return("Something went wrong..");
            }

            var rule = _context.RuleSets.Where(x => x.Id == ruleId).FirstOrDefault();

            var hMPlayers = _context.Players.Where(x => players.Contains(x.PlayerInfoId.ToString()) && x.ApiId != 0).ToList();

            var forwards   = 0;
            var defencemen = 0;
            var goalies    = 0;

            foreach (var player in hMPlayers)
            {
                //Count every position
                if (player.Position == "C" || player.Position == "LW" || player.Position == "RW")
                {
                    forwards++;
                }
                else if (player.Position == "D")
                {
                    defencemen++;
                }
                else if (player.Position == "G")
                {
                    goalies++;
                }

                //Check to make sure the user hasn't exceeded the player position limit
                if (forwards > rule.maxForwards)
                {
                    return("Too many forwards!");
                }
                else if (defencemen > rule.maxDefensemen)
                {
                    return("Too many defencemen!");
                }
                else if (goalies > rule.maxGoalies)
                {
                    return("Too many goalies!");
                }
            }
            //Check if team is too big or too small
            if ((forwards + defencemen + goalies) > rule.maxPlayers)
            {
                return("Too many players!");
            }
            else if ((forwards + defencemen + goalies) < rule.maxPlayers)
            {
                return($"{rule.maxPlayers - (forwards + defencemen + goalies)} more players are required.");
            }

            //All validation succeeded

            HMTeam team = new HMTeam();

            if (anyTeam.Any())
            {
                //Update
                team = anyTeam.FirstOrDefault();

                if (team.TeamInfo.Name != name)
                {
                    team.TeamInfo.Name = name;
                    _context.TeamInfo.Attach(team.TeamInfo);
                    _context.Entry(team.TeamInfo).Property(x => x.Name).IsModified = true;
                    await _context.SaveChangesAsync();
                }

                players = players.Skip(1).ToArray();
                int[] newPlayers = Array.ConvertAll(players, s => int.Parse(s));
                var   oldPlayers = _context.Players.Include(x => x.Team).Include(x => x.PlayerInfo).Where(x => x.Team.PoolId == id && x.Team.UserId == _userManager.GetUserId(User)).Select(x => x.PlayerInfo.Id).ToArray();
                var   sameTeam   = Enumerable.SequenceEqual(oldPlayers, newPlayers);

                if (sameTeam)
                {
                    return("name updated");
                }

                var existingPlayers = _context.Players.Include(x => x.Team).Where(x => x.Team.Id == anyTeam.FirstOrDefault().Id).ToList();
                _context.Players.RemoveRange(existingPlayers);
                await _context.SaveChangesAsync();
            }
            else
            {
                //Add
                HMTeamInfo teamInfo = new HMTeamInfo();
                teamInfo.Name = name;

                await _context.TeamInfo.AddAsync(teamInfo);

                await _context.SaveChangesAsync();


                team.TeamInfoId = teamInfo.Id;
                team.PoolId     = id;
                team.UserId     = _userManager.GetUserId(User);

                await _context.Teams.AddAsync(team);

                await _context.SaveChangesAsync();
            }

            List <HMPlayer> newlyGeneratedPlayers = new List <HMPlayer>();

            foreach (var player in hMPlayers)
            {
                newlyGeneratedPlayers.Add(new HMPlayer
                {
                    Position     = player.Position,
                    Overall      = player.Overall,
                    TeamId       = team.Id,
                    PlayerInfoId = player.PlayerInfoId
                });
            }

            await _context.Players.AddRangeAsync(newlyGeneratedPlayers);

            await _context.SaveChangesAsync();

            return("success");
        }