public async Task <IActionResult> SignUp([Bind("TeamName, Password, CompetitionID")] Team team)
        {
            if (ModelState.IsValid)
            {
                //BCryptPasswordHash bCryptPasswordHash = new BCryptPasswordHash();
                var salt         = BCryptPasswordHash.GetRandomSalt();
                var hashPassword = BCryptPasswordHash.HashPassword(team.Password, salt);
                team.Password = hashPassword;
                team.Salt     = salt;
                _context.Add(team);
                //get userId
                //var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                //Migrating to new way to get user object
                var user = await _userManager.GetUserAsync(HttpContext.User);

                TeamUser teamUser = new TeamUser();
                teamUser.UserId   = user.Id;
                teamUser.UserName = user.UserName;

                teamUser.TeamId = team.TeamID;
                _context.Add(teamUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Competitions"));
            }
            ViewData["CompetitionID"] = team.CompetitionID;
            return(View());
        }
        public async Task <IActionResult> Create([Bind("ID,CategoryName")] CategoryDefault categoryDefault)
        {
            if (ModelState.IsValid)
            {
                _context.Add(categoryDefault);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoryDefault));
        }
        public async Task <IActionResult> Create([Bind("TeamID,TeamName,Password,CompetitionID")] Team team)
        //public async Task<IActionResult> Create([Bind("TeamID, TeamName, Score")] Team team)
        {
            if (ModelState.IsValid)
            {
                _context.Add(team);
                await _context.SaveChangesAsync();

                //return RedirectToAction(nameof(Index));
                return(RedirectToAction("Index", "Teams", new { id = team.CompetitionID }));
            }
            return(View(team));
            //return RedirectToAction("Index", "Teams", new { id = team.CompetitionID });
        }
        public async Task <IActionResult> Details([Bind("ID, Flag, CompetitionID")] Challenge challenge, int?id)
        {
            if (challenge.Flag == null)
            {
                var temp_challenge1 = await _context.Challenges
                                      .FirstOrDefaultAsync(m => m.ID == challenge.ID);

                var competition1 = await _context.Competitions.FindAsync(temp_challenge1.CompetitionID);

                string bucketName = competition1.BucketName;
                var    category   = await _context.CompetitionCategories.FindAsync(temp_challenge1.CompetitionCategoryID);

                string folderName = category.CategoryName;
                if (temp_challenge1.FileName != null)
                {
                    string fileName     = temp_challenge1.FileName;
                    Regex  pattern      = new Regex("[+]");
                    string tempFileName = pattern.Replace(fileName, "%2B");
                    tempFileName.Replace(' ', '+');
                    ViewData["FileLink"] = "https://s3-ap-southeast-1.amazonaws.com/" + bucketName + "/" + folderName + "/" + tempFileName;
                }
                ViewData["CompetitionID"] = temp_challenge1.CompetitionID;
                ViewData["ChallengeID"]   = temp_challenge1.ID;

                ViewData["Invalid"]   = true;
                ViewData["WrongFlag"] = false;
                return(View(temp_challenge1));
            }

            Team team = null;

            var competition = await _context.Competitions
                              .Include(c => c.CompetitionCategories)
                              .ThenInclude(cc => cc.Challenges)
                              .Include(c => c.Teams)
                              .ThenInclude(t => t.TeamUsers)
                              .AsNoTracking()
                              .FirstOrDefaultAsync(m => m.ID == challenge.CompetitionID);

            var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            foreach (var Team in competition.Teams)
            {
                foreach (var TeamUser in Team.TeamUsers)
                {
                    if (TeamUser.UserId.Equals(userId))
                    {
                        team = Team;
                        break;
                    }
                }
            }

            //Get all challenges this team has solved
            var teamChallengesList = await _context.Teams
                                     .Include(t => t.TeamChallenges)
                                     .AsNoTracking()
                                     .FirstOrDefaultAsync(m => m.TeamID == team.TeamID);

            foreach (var teamChallenges in teamChallengesList.TeamChallenges)
            {
                if (teamChallenges.ChallengeId == challenge.ID)
                {
                    if (teamChallenges.Solved == true)
                    {
                        return(RedirectToAction("Details", "Challenges", new { id }));
                    }
                }
            }

            var localvarchallenge = await _context.Challenges
                                    .AsNoTracking()
                                    .FirstOrDefaultAsync(m => m.ID == challenge.ID);

            //if (ModelState.IsValid)
            //{
            //    _context.Add(challenge);
            //    await _context.SaveChangesAsync();
            //    return RedirectToAction(nameof(Index));
            //}

            //if (challenge.CompetitionID == null)
            //{
            //    return NotFound();
            //}

            var temp_challenge = await _context.Challenges
                                 .FirstOrDefaultAsync(m => m.ID == challenge.ID);

            if (temp_challenge == null)
            {
                return(NotFound());
            }
            // Flag is correct
            if (challenge.Flag.Equals(temp_challenge.Flag))
            {
                //Add entry to TeamChallenge
                TeamChallenge teamChallenge = new TeamChallenge();
                teamChallenge.ChallengeId = localvarchallenge.ID;
                teamChallenge.TeamId      = team.TeamID;
                teamChallenge.Solved      = true;
                _context.Add(teamChallenge);
                await _context.SaveChangesAsync();

                //Add entry to chain
                //Block and block data
                Block block = new Block();
                block.TimeStamp       = DateTime.Now;
                block.CompetitionID   = challenge.CompetitionID;
                block.TeamID          = team.TeamID;
                block.ChallengeID     = localvarchallenge.ID;
                block.TeamChallengeID = teamChallenge.TeamChallengeID;
                block.Score           = localvarchallenge.Value;
                //Previous Hash
                Blockchain blockchain  = new Blockchain(_context);
                Block      latestBlock = await blockchain.GetLatestBlock();

                block.PreviousHash = latestBlock.Hash;
                //Current Hash
                string data = block.TimeStamp + ";" + block.CompetitionID + ";" + block.TeamID + ";" + block.ChallengeID + ";" + block.TeamChallengeID + ";" + block.Score + ";" + block.PreviousHash;
                block.Hash = GenerateSHA512String(data);

                _context.Add(block);
                await _context.SaveChangesAsync();

                //Add points to team score
                team.Score += localvarchallenge.Value;
                _context.Update(team);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index", "Challenges", new { id = challenge.CompetitionID }));
            }
            else
            {
                //Wrong flag
                TeamChallenge teamChallenge = new TeamChallenge();
                teamChallenge.ChallengeId = localvarchallenge.ID;
                teamChallenge.TeamId      = team.TeamID;
                teamChallenge.Solved      = false;
                _context.Add(teamChallenge);
                await _context.SaveChangesAsync();

                var Challenge = await _context.Challenges
                                .FirstOrDefaultAsync(m => m.ID == id);

                if (Challenge == null)
                {
                    return(NotFound());
                }
                //Stop field from being populated at View
                Challenge.Flag = null;

                var Competition = await _context.Competitions.FindAsync(Challenge.CompetitionID);

                string bucketName = Competition.BucketName;
                var    category   = await _context.CompetitionCategories.FindAsync(Challenge.CompetitionCategoryID);

                string folderName = category.CategoryName;
                if (Challenge.FileName != null)
                {
                    string fileName     = Challenge.FileName;
                    Regex  pattern      = new Regex("[+]");
                    string tempFileName = pattern.Replace(fileName, "%2B");
                    tempFileName.Replace(' ', '+');
                    ViewData["FileLink"] = "https://s3-ap-southeast-1.amazonaws.com/" + bucketName + "/" + folderName + "/" + tempFileName;
                }
                ViewData["CompetitionID"] = Challenge.CompetitionID;
                ViewData["ChallengeID"]   = Challenge.ID;

                //if (ValidateUserJoined(Challenge.CompetitionID).Result == true)
                //{
                ViewData["Invalid"]   = false;
                ViewData["WrongFlag"] = true;
                return(View(Challenge));
                //}
            }
        }
        //public async Task<IActionResult> Create([Bind("ID,CompetitionName,Status,BucketName")] Competition competition, [Bind("CategoryName")] CompetitionCategory competitionCategory, string[] SelectedCategories)
        public async Task <IActionResult> Create(CategoriesViewModelIEnumerable model)
        //public async Task<IActionResult> Create(string[] CategoriesList)
        {
            /*foreach (var CategoryName in model.SelectedCategories)
             * {
             *  Console.WriteLine(CategoryName);
             * }*/
            //Console.WriteLine(model.competition.BucketName);
            //Tested and working^
            //Console.WriteLine(model.SelectedCategories.ElementAt(0));
            //Console.WriteLine(competitionCategory.Categories.ElementAt(0).CategoryName);
            if (model.SelectedCategories == null)
            {
                return(RedirectToAction("Create"));
            }

            model.Competition.Status = "Upcoming";
            if (ModelState.IsValid)
            {
                //Generate bucketname programtically
                model.Competition.BucketName            = GenerateBucketName(model.Competition.CompetitionName);
                model.Competition.CompetitionCategories = new Collection <CompetitionCategory>();
                foreach (var CategoryName in model.SelectedCategories)
                {
                    //model.competitionCategory = _context.CompetitionCategories.Find("CompetitionID");
                    //model.competitionCategory.CompetitionID = model.competition.ID;
                    //model.competitionCategory.CategoryName = CategoryName;

                    //competitionCategory.CategoryName = CategoryName;
                    //competitionCategory.CompetitionID = model.competition.ID;

                    //CompetitionCategoriesTempList.Add

                    model.Competition.CompetitionCategories.Add(new CompetitionCategory {
                        CompetitionID = model.Competition.ID, CategoryName = CategoryName
                    });

                    //competitionCategory.competitionID = _context.Competitions.Find("ID");\
                    //model.competition = new Competition();
                    //model.competition.CompetitionCategories.Add(new CompetitionCategory { CompetitionID = model.competition.ID, CategoryName = CategoryName });
                    //await _context.SaveChangesAsync();
                }
                _context.Add(model.Competition);
                await _context.SaveChangesAsync();

                try
                {
                    PutBucketResponse response = await S3Client.PutBucketAsync(model.Competition.BucketName);

                    if (response.HttpStatusCode == HttpStatusCode.OK)
                    {
                        //return RedirectToAction("");
                    }
                    else
                    {
                        //return RedirectToAction("");
                        //return RedirectToAction(nameof(Index));
                    }
                }
                catch (AmazonS3Exception e)
                {
                    ViewData["Exception"] = e.Message;
                    //return View();
                }
                //return RedirectToAction(nameof(Index));
            }
            else
            {
            }
            //return View(competition);
            //return View(model);
            //Testing create folder dynamically
            foreach (var CategoryName in model.SelectedCategories)
            {
                CreateFolder(model.Competition.BucketName, CategoryName);
            }
            //Testing create folder dynamically
            return(RedirectToAction("Index"));
        }