public ActionResult NewPlatoonAssignmentsData(DataSourceRequest command, Guid id, Guid?memberId, Guid?guildId = null)
        {
            DataSourceResult gridModel;

            var tbp = db.TerritoryBattlePhases.Find(id);

            if (guildId == null)
            {
                guildId = tbp.TerritoryBattle.Guild_Id;
            }
            var ds        = new DataTable();
            var newReport = (IEnumerable <PhaseReport>)HttpContext.Cache.Get("PlatoonAssignments" + id + guildId);

            if (newReport == null)
            {
                newReport = db.PhaseReports.Where(x => x.TerritoryBattlePhase_Id == id && x.GuildId == guildId && x.MemberShip_Id == null);
                if (!newReport.Any())
                {
                    using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SwgohDb"].ConnectionString))
                    {
                        var sqlComm = new SqlCommand("sp_RequiredPlatoonCharacters", conn);
                        sqlComm.Parameters.AddWithValue("@phaseGuid", id);

                        sqlComm.CommandType = System.Data.CommandType.StoredProcedure;

                        var da = new SqlDataAdapter {
                            SelectCommand = sqlComm
                        };

                        da.Fill(ds);

                        ds.Columns.Add("Member_Id");
                        Guid?currentCharId    = Guid.Empty;
                        var  memberCharacters = new List <MemberCharacter>();
                        var  assignedChars    = 0;

                        foreach (DataRow row in ds.Rows)
                        {
                            if (currentCharId != row.Field <Guid>("Character_Id"))
                            {
                                currentCharId    = row.Field <Guid>("Character_Id");
                                memberCharacters = db.MemberCharacters.Where(x => x.Character_Id == currentCharId &&
                                                                             x.Member.Guild_Id == guildId &&
                                                                             x.Stars >= tbp.RequiredStars)
                                                   .OrderBy(x => x.Power)
                                                   .ThenBy(x => x.Stars)
                                                   .ThenBy(x => x.Level)
                                                   .ThenBy(x => x.Gear).ToList();
                                assignedChars = 0;
                            }

                            try
                            {
                                row[1] = memberCharacters[assignedChars].Id;
                            }
                            catch
                            {
                                row[1] = DBNull.Value;
                            }
                            assignedChars++;
                        }
                        newReport = ds.AsEnumerable().Select(
                            dataRow => new PhaseReport
                        {
                            Id = Guid.NewGuid(),
                            PlatoonCharacter_Id     = dataRow.Field <Guid?>("PlatoonCharacter_Id"),
                            PlatoonCharacter        = db.PlatoonCharacters.Find(dataRow.Field <Guid?>("PlatoonCharacter_Id")),
                            TerritoryBattlePhase_Id = dataRow.Field <Guid>("TerritoryBattlePhase_Id"),
                            TerritoryBattlePhase    = db.TerritoryBattlePhases.Find(dataRow.Field <Guid>("TerritoryBattlePhase_Id")),
                            MemberCharacter_Id      = dataRow.Field <Guid?>("Character_Id"),
                            MemberCharacter         = db.MemberCharacters.Find(dataRow.Field <Guid?>("Character_Id")),
                            GuildId = guildId
                        }).ToList();

                        db.BulkInsert(newReport);
                    }
                }
                HttpContext.Cache.Insert("PlatoonAssignments" + id + guildId, newReport, null, Cache.NoAbsoluteExpiration, new TimeSpan(24, 0, 0));
            }
            if (memberId.HasValue)
            {
                try
                {
                    gridModel = db.PhaseReports.Where(x => x.TerritoryBattlePhase_Id == id && x.GuildId == guildId && x.MemberShip_Id == null && x.MemberCharacter.Member_Id == memberId).ToList()
                                .ToDataSourceResult(command, Mapper.Map <PhaseReport, PlatoonAssignmentsModel>);
                    //var gridModel2 = newReport.Where(x => x.MemberCharacter.Member_Id == memberId).ToList();
                    //gridModel = newReport.Where(x => x.MemberCharacter.Member_Id == memberId).ToList()
                    // .ToDataSourceResult(command, Mapper.Map<PhaseReport, PlatoonAssignmentsModel>);
                }
                catch (Exception exception)
                {
                    gridModel = null;
                }
            }
            else
            {
                gridModel = (DataSourceResult)HttpContext.Cache.Get("PlatoonAssignmentsGrid" + id + guildId);
                if (gridModel == null)
                {
                    gridModel = newReport.ToDataSourceResult(command, Mapper.Map <PhaseReport, PlatoonAssignmentsModel>);
                    HttpContext.Cache.Insert("PlatoonAssignmentsGrid" + id + guildId, gridModel, null, Cache.NoAbsoluteExpiration, new TimeSpan(24, 0, 0));
                }
            }
            return(Json(gridModel));
        }
        public ActionResult Create()
        {
            var territoryBattle = new TerritoryBattle
            {
                Id        = Guid.NewGuid(),
                Guild_Id  = userDb.Users.FirstOrDefault(x => x.UserName == User.Identity.Name).Guild_Id,
                StartDate = DateTime.Now,
                IsActive  = true
            };

            List <TerritoryBattlePhase> territoryBattlePhases = new List <TerritoryBattlePhase>()
            {
                new TerritoryBattlePhase()
                {
                    Id = Guid.NewGuid(),
                    HasSecondTerritory = true,
                    HasThirdTerritory  = true,
                    RequiredStars      = 5,
                    Phase = 4,
                    TerritoryBattle_Id = territoryBattle.Id,
                },
                new TerritoryBattlePhase()
                {
                    Id = Guid.NewGuid(),
                    HasSecondTerritory = true,
                    HasThirdTerritory  = true,
                    RequiredStars      = 6,
                    Phase = 5,
                    TerritoryBattle_Id = territoryBattle.Id,
                },
                new TerritoryBattlePhase()
                {
                    Id = Guid.NewGuid(),
                    HasSecondTerritory = true,
                    HasThirdTerritory  = true,
                    RequiredStars      = 7,
                    Phase = 6,
                    TerritoryBattle_Id = territoryBattle.Id,
                }
            };
            List <PhaseTerritory> phaseTerritories = new List <PhaseTerritory>()
            {
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Middle",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Bottom",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Top",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 4)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Middle",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Bottom",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Top",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 5)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Middle",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Bottom",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6)
                },
                new PhaseTerritory()
                {
                    Id                      = Guid.NewGuid(),
                    PhaseLocation           = "Top",
                    TerritoryBattlePhase_Id = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6).Id,
                    TerritoryBattlePhase    = territoryBattlePhases.FirstOrDefault(x => x.Phase == 6)
                },
            };

            List <TerritoryPlatoon> territoryPlatoons = new List <TerritoryPlatoon>();

            foreach (var phaseTerritory in territoryBattlePhases)
            {
                List <TerritoryPlatoon> territoryPlatoonsAdd = new List <TerritoryPlatoon>()
                {
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 1,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    },
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 2,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    },
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 3,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    },
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 4,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    },
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 5,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    },
                    new TerritoryPlatoon()
                    {
                        Id                = Guid.NewGuid(),
                        PlatoonNumber     = 6,
                        PhaseTerritory_Id = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).Id,
                        PhaseTerritory    = phaseTerritories.FirstOrDefault(x => x.PhaseLocation == "Middle" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase)
                    }
                };

                territoryPlatoons.AddRange(territoryPlatoonsAdd);

                if (phaseTerritory.HasSecondTerritory)
                {
                    territoryPlatoonsAdd = new List <TerritoryPlatoon>()
                    {
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 1,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 2,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 3,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 4,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 5,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 6,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Bottom" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                    };

                    territoryPlatoons.AddRange(territoryPlatoonsAdd);
                }


                if (phaseTerritory.HasThirdTerritory)
                {
                    territoryPlatoonsAdd = new List <TerritoryPlatoon>()
                    {
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 1,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 2,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 3,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 4,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 5,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                        new TerritoryPlatoon()
                        {
                            Id                = Guid.NewGuid(),
                            PlatoonNumber     = 6,
                            PhaseTerritory_Id = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault().Id,
                            PhaseTerritory    = phaseTerritories.Where(x => x.PhaseLocation == "Top" && x.TerritoryBattlePhase.Phase == phaseTerritory.Phase).FirstOrDefault()
                        },
                    };

                    territoryPlatoons.AddRange(territoryPlatoonsAdd);
                }
            }

            List <PlatoonCharacter> platoonCharacters = new List <PlatoonCharacter>();
            List <PlatoonShip>      platoonShips      = new List <PlatoonShip>();

            foreach (var platoon in territoryPlatoons)
            {
                if (platoon.PhaseTerritory.PhaseLocation != "Top")
                {
                    var platoonCharactersAdd = new List <PlatoonCharacter>()
                    {
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 1, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 2, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 3, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 4, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 5, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 6, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 7, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 8, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 9, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 10, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 11, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 12, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 13, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 14, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonCharacter()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 15, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                    };
                    platoonCharacters.AddRange(platoonCharactersAdd);
                }
                else
                {
                    List <PlatoonShip> platoonShipsAdd = new List <PlatoonShip>()
                    {
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 1, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 2, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 3, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 4, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 5, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 6, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 7, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 8, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 9, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 10, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 11, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 12, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 13, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 14, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                        new PlatoonShip()
                        {
                            Id = Guid.NewGuid(), PlatoonPosition = 15, TerritoryPlatoon_Id = platoon.Id, TerritoryPlatoon = platoon
                        },
                    };
                    platoonShips.AddRange(platoonShipsAdd);
                }
            }

            if (ModelState.IsValid)
            {
                db.TerritoryBattles.Add(territoryBattle);
                db.SaveChanges();
                db.BulkInsert(territoryBattlePhases);
                db.BulkInsert(phaseTerritories);
                db.BulkInsert(territoryPlatoons);
                db.BulkInsert(platoonCharacters);
                db.BulkInsert(platoonShips);
                return(RedirectToAction("Index", "TerritoryBattles", new { }));
            }

            return(View(territoryBattle));
        }
        private void UpdateRoster(Guid id, Guild guild)
        {
            db = new SwgohDb();
            IEnumerable <Member>    members    = db.Members.Include(x => x.MemberCharacters).Include(x => x.MemberShips).Where(x => x.Guild_Id == id).ToList();
            IEnumerable <Character> characters = db.Characters.ToList();
            IEnumerable <Ship>      ships      = db.Ships.ToList();

            HtmlWeb      web = new HtmlWeb();
            HtmlDocument doc = web.Load(guild.UrlExt + "gp/");

            string guildMemberTable = doc.DocumentNode.SelectNodes("/html/body/div[3]/div[1]")[0].InnerHtml;

            guildMemberTable = guildMemberTable.Substring(guildMemberTable.IndexOf("<tbody>") + 7);
            Regex regexChar = new Regex(@"\n");
            Regex regex     = new Regex(@"<tr>");

            string[] substrings = regex.Split(guildMemberTable);
            //substrings = substrings.Skip(1).ToArray();
            List <string> listMembers = substrings.ToList();

            //listMembers.RemoveRange(0,2);

            listMembers.Remove("\n");

            List <Member>          newMembers          = new List <Member>();
            List <Member>          updateMembers       = new List <Member>();
            List <MemberCharacter> memberCharactersAdd = new List <MemberCharacter>();
            List <MemberShip>      memberShipsAdd      = new List <MemberShip>();

            List <Member> memberDelete = new List <Member>();

            List <string> memberExt = new List <string>();

            foreach (var member in listMembers)
            {
                string[] memberSplit = member.Split('"');
                memberExt.Add("https://swgoh.gg" + memberSplit[3] + "characters/");
            }

            foreach (var member in members)
            {
                if (!memberExt.Any(x => x.Contains(member.UrlExt)))
                {
                    memberDelete.Add(db.Members.FirstOrDefault(x => x.UrlExt == member.UrlExt));
                    db.SaveChanges();
                    db = new SwgohDb();
                }
            }
            foreach (var member in memberDelete)
            {
                var phaseReportChars = db.PhaseReports.Where(x => x.MemberCharacter.Member_Id == member.Id).ToList();
                db.BulkDelete(phaseReportChars);
                db = new SwgohDb();
                var phaseReportShips = db.PhaseReports.Where(x => x.MemberShip.Member_Id == member.Id).ToList();
                db.BulkDelete(phaseReportShips);
                db = new SwgohDb();
            }
            db.BulkDelete(memberDelete);
            db = new SwgohDb();

            foreach (var member in listMembers)
            {
                Member   guildMember = new Member();
                string[] memberSplit = member.Split('"');
                string   charHref    = "https://swgoh.gg" + memberSplit[3] + "characters/";
                string   shipHref    = "https://swgoh.gg" + memberSplit[3] + "ships/";
                string   name        = Regex.Replace(memberSplit[4], "(?s).*?(?<=<strong>)", String.Empty); // memberSplit[2].Substring(10).Replace("</strong>\n</a>\n</td>\n<td class=", "");
                name = name.Remove(name.IndexOf("</strong>", StringComparison.Ordinal));

                string toConvertChar = memberSplit[8].Replace(">", "").Replace(" ", "").Replace("</td\n<tdclass=", "");
                string toConvertShip = memberSplit[10].Replace(" ", "").Replace(">", "").Replace("</td\n</tr\n", "")
                                       .Replace("</tbody\n</table\n</div\n</li\n", "").Replace("</ul\n</div\n", "");

                if (members.Any(x => x.UrlExt.Equals(charHref)))
                {
                    guildMember                = members.FirstOrDefault(x => x.UrlExt.Equals(charHref));
                    guildMember.Name           = name;
                    guildMember.DisplayName    = HttpUtility.HtmlDecode(name);
                    guildMember.CharacterPower = Convert.ToInt32(toConvertChar);
                    guildMember.ShipPower      = Convert.ToInt32(toConvertShip);
                    updateMembers.Add(guildMember);
                }
                else
                {
                    guildMember.Id             = Guid.NewGuid();
                    guildMember.Name           = name;
                    guildMember.DisplayName    = HttpUtility.HtmlDecode(name);
                    guildMember.UrlExt         = charHref;
                    guildMember.Guild_Id       = guild.Id;
                    guildMember.CharacterPower = Convert.ToInt32(toConvertChar);
                    guildMember.ShipPower      = Convert.ToInt32(toConvertShip);
                    newMembers.Add(guildMember);
                }

                var memberCharacters = new List <MemberCharacter>();
                try
                {
                    memberCharacters = guildMember.MemberCharacters.ToList();// db.MemberCharacters.Where(x => x.Member_Id.Equals(guildMember.Id)).ToList();
                }
                catch
                {
                }
                string charHtml;

                HtmlDocument docMember = web.Load(charHref);
                try
                {
                    charHtml = docMember.DocumentNode.SelectNodes("//li[@class='media list-group-item p-a collection-char-list']")[0].InnerHtml;
                }
                catch (Exception ex)
                {
                    continue;
                }
                string[]      character      = regexChar.Split(charHtml);
                List <string> listCharacters = character.ToList();

                listCharacters.RemoveAll(x => x.Equals(""));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"row\">"));
                listCharacters.RemoveAll(x => x.Equals("</a>"));
                listCharacters.RemoveAll(x => x.Equals("</div>"));
                listCharacters.RemoveAll(x => x.Equals("</span>"));
                listCharacters.RemoveAll(x => x.Equals("<span class=\"collection-char-gp-label-value\">"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"collection-char-gp-progress\">"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"char-portrait-full-gear\"></div>"));
                listCharacters.RemoveAll(x => x.Equals("<span class=\"collection-char-gp-label-percent\">%</span>"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"collection-char-gp-label\">"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"collection-char collection-char-light-side\">"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"collection-char collection-char-dark-side\">"));
                listCharacters.RemoveAll(x => x.Equals("<div class=\"col-xs-6 col-sm-3 col-md-3 col-lg-2\">"));

                var newMemberCharacter = new MemberCharacter
                {
                    Member_Id = guildMember.Id,
                    Id        = Guid.NewGuid()
                };

                foreach (var item in listCharacters)
                {
                    if (item.Contains("<div class=\"char-portrait-full-level"))
                    {
                        newMemberCharacter.Level = Convert.ToInt16(item.Trim().Substring(38, 2).Replace("<", ""));
                    }
                    else if (item.Contains("<div class=\"char-portrait-full-gear-level\">"))
                    {
                        var romanNum = Regex.Replace(item, "(?s).*?(?<=\">)", String.Empty);
                        romanNum = romanNum.Remove(romanNum.IndexOf("</", StringComparison.Ordinal));
                        switch (romanNum)
                        {
                        case "I":
                            newMemberCharacter.Gear = 1;
                            break;

                        case "II":
                            newMemberCharacter.Gear = 2;
                            break;

                        case "III":
                            newMemberCharacter.Gear = 3;
                            break;

                        case "IV":
                            newMemberCharacter.Gear = 4;
                            break;

                        case "V":
                            newMemberCharacter.Gear = 5;
                            break;

                        case "VI":
                            newMemberCharacter.Gear = 6;
                            break;

                        case "VII":
                            newMemberCharacter.Gear = 7;
                            break;

                        case "VIII":
                            newMemberCharacter.Gear = 8;
                            break;

                        case "IX":
                            newMemberCharacter.Gear = 9;
                            break;

                        case "X":
                            newMemberCharacter.Gear = 10;
                            break;

                        case "XI":
                            newMemberCharacter.Gear = 11;
                            break;

                        case "XII":
                            newMemberCharacter.Gear = 12;
                            break;
                        }
                    }
                    else if (item.Contains("<div class=\"collection-char-gp\""))
                    {
                        try
                        {
                            var toConvert = item.Substring(0, item.LastIndexOf('/'));
                            toConvert = toConvert.Substring(toConvert.LastIndexOf('r') + 2);
                            newMemberCharacter.Power = Convert.ToInt32(toConvert.Replace(",", ""));
                        }
                        catch
                        {
                            newMemberCharacter.Power = 0;
                        }
                    }
                    else if (item.Contains("<div class=\"star ") && !item.Contains("star-inactive"))
                    {
                        newMemberCharacter.Stars = Convert.ToInt16(item.Trim().Substring(21, 1));
                    }
                    else if (item.Contains("<img class=\"char-portrait-full-img\""))
                    {
                        var startIndex = item.IndexOf("alt=") + 5;
                        var endIndex   = item.IndexOf("height=") - 2 - startIndex;
                        //string charName = Regex.Replace(item, "<.*?>", String.Empty);
                        string charName = item.Substring(startIndex, endIndex);
                        IEnumerable <Character> charNames = characters.Where(x => x.Name.Equals(charName.Trim())).ToList();

                        if (charNames.Count() == 1)
                        {
                            newMemberCharacter.Character_Id = charNames.FirstOrDefault().Id;
                        }
                        else
                        {
                            if (charName.Contains("Fulcrum"))
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Equals("Ahsoka Tano (Fulcrum)")).Id;
                            }
                            else if (charName.Equals("Ahsoka Tano") || charName.Equals("hsoka Tano"))
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Equals("Ahsoka Tano")).Id;
                            }
                            else if (charName.Equals("Jawa"))
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Equals("Jawa")).Id;
                            }
                            else if (charName.Equals("Han Solo"))
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Equals("Han Solo")).Id;
                            }
                            else if (charName.Equals("Stormtrooper"))
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Equals("Stormtrooper")).Id;
                            }
                            else
                            {
                                newMemberCharacter.Character_Id = charNames.FirstOrDefault(x => x.Name.Substring(1).Contains(charName)).Id;
                            }
                        }
                    }
                    else if (item.Contains("<div class=\"collection-char-name\">"))
                    {
                        if (newMemberCharacter.Stars != null)
                        {
                            if (memberCharacters.Any(x => x.Character_Id.Equals(newMemberCharacter.Character_Id)))
                            {
                                MemberCharacter memberCharacterUpdate = memberCharacters.FirstOrDefault(x => x.Character_Id.Equals(newMemberCharacter.Character_Id));

                                memberCharacterUpdate.Level = newMemberCharacter.Level;
                                memberCharacterUpdate.Power = newMemberCharacter.Power;
                                memberCharacterUpdate.Stars = newMemberCharacter.Stars;
                                memberCharacterUpdate.Gear  = newMemberCharacter.Gear;

                                memberCharacters.Remove(memberCharacters.FirstOrDefault(x => x.Character_Id.Equals(newMemberCharacter.Character_Id)));
                                memberCharacters.Add(memberCharacterUpdate);
                            }
                            else
                            {
                                memberCharactersAdd.Add(newMemberCharacter);
                            }
                        }
                        newMemberCharacter = new MemberCharacter
                        {
                            Member_Id = guildMember.Id,
                            Id        = Guid.NewGuid()
                        };
                    }
                }
                if (memberCharacters.Count() != 0)
                {
                    db.BulkUpdate(memberCharacters);
                }
                db = new SwgohDb();
                List <MemberShip> memberShips = db.MemberShips.Where(x => x.Member_Id.Equals(guildMember.Id)).ToList();

                string shipHtml;

                HtmlDocument docShip = web.Load(shipHref);
                try
                {
                    shipHtml = docShip.DocumentNode.SelectNodes("//li[@class='media list-group-item p-a collection-char-list']")[0].InnerHtml;
                }
                catch
                {
                    continue;
                }
                string[]      ship      = regexChar.Split(shipHtml);
                List <string> listShips = ship.ToList();

                listShips.RemoveAll(x => x.Equals(""));
                listShips.RemoveAll(x => x.Equals("<div class=\"row\">"));
                listShips.RemoveAll(x => x.Equals("</a>"));
                listShips.RemoveAll(x => x.Equals("</div>"));
                listShips.RemoveAll(x => x.Equals("</span>"));
                listShips.RemoveAll(x => x.Equals("<span class=\"collection-char-gp-label-value\">"));
                listShips.RemoveAll(x => x.Equals("    \">"));
                listShips.RemoveAll(x => x.Equals("    "));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-ship-primary\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-ship-main\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-ship collection-ship-light-side\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-ship collection-ship-dark-side\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"col-sm-6 col-md-6 col-lg-4\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"ship-portrait-full-frame\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"ship-portrait-full-frame-overlay\"></div>"));
                listShips.RemoveAll(x => x.Equals("<div class=\"ship-portrait-full-frame-image\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-ship-secondary\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-char-gp-progress\">"));
                listShips.RemoveAll(x => x.Equals("<div class=\"collection-char-gp-label\">"));
                listShips.RemoveAll(x => x.Equals("<span class=\"collection-char-gp-label-percent\">%</span>"));
                listShips.RemoveAll(x => x.StartsWith("<div class=\"collection-ship-crew"));
                listShips.RemoveAll(x => x.StartsWith("<div class=\"star star"));
                listShips.RemoveAll(x => x.StartsWith("<div class=\"char-portrait"));

                MemberShip newMemberShip = new MemberShip
                {
                    Member_Id = guildMember.Id,
                    Id        = Guid.NewGuid()
                };

                foreach (var item in listShips)
                {
                    if (item.Contains("<div class=\"ship-portrait-full-frame-level"))
                    {
                        newMemberShip.Level = Convert.ToInt16(item.Trim().Substring(44, 2).Replace("<", ""));
                    }
                    else if (item.Contains("\"Power "))
                    {
                        newMemberShip.Power = item.Trim().Substring(83).Replace("\">", "");
                        try
                        {
                            var toConvert = item.Substring(0, item.LastIndexOf('/'));
                            toConvert = toConvert.Substring(toConvert.LastIndexOf('r') + 2);
                            newMemberShip.ShipPower = Convert.ToInt32(toConvert.Replace(",", ""));
                        }
                        catch
                        {
                            newMemberShip.ShipPower = 0;
                        }
                    }
                    else if (item.Contains("ship-portrait-full-star") && !item.Contains("ship-portrait-full-star-inactive") && !item.Contains("stars"))
                    {
                        if (newMemberShip.Stars == null)
                        {
                            newMemberShip.Stars = 1;
                        }
                        else
                        {
                            newMemberShip.Stars = newMemberShip.Stars + 1;
                        }
                    }
                    else if (item.Contains("<a class=\"collection-ship-name-link\""))
                    {
                        var startIndex = item.IndexOf(">") + 1;
                        var endIndex   = item.IndexOf("</a") - startIndex;
                        //string charName = Regex.Replace(item, "<.*?>", String.Empty);
                        string shipName = item.Substring(startIndex, endIndex);
                        //var shipName = Regex.Replace(item, "<.*?>", string.Empty);
                        IEnumerable <Ship> shipNames = ships.Where(x => x.Name.Equals(shipName.Trim())).ToList();

                        if (shipNames.Count() == 1)
                        {
                            newMemberShip.Ship_Id = shipNames.FirstOrDefault().Id;
                        }
                        else
                        {
                            var blah = 1;
                        }

                        if (newMemberShip.Stars != null)
                        {
                            if (memberShips.Any(x => x.Ship_Id.Equals(newMemberShip.Ship_Id)))
                            {
                                MemberShip memberShipUpdate = memberShips.FirstOrDefault(x => x.Ship_Id.Equals(newMemberShip.Ship_Id));

                                memberShipUpdate.Level     = newMemberShip.Level;
                                memberShipUpdate.Power     = newMemberShip.Power;
                                memberShipUpdate.Stars     = newMemberShip.Stars;
                                memberShipUpdate.ShipPower = newMemberShip.ShipPower;

                                memberShips.Remove(memberShips.FirstOrDefault(x => x.Ship_Id.Equals(newMemberShip.Ship_Id)));
                                memberShips.Add(memberShipUpdate);
                            }
                            else
                            {
                                memberShipsAdd.Add(newMemberShip);
                            }
                        }
                        newMemberShip = new MemberShip
                        {
                            Member_Id = guildMember.Id,
                            Id        = Guid.NewGuid()
                        };
                    }
                }
                if (memberShips.Count != 0)
                {
                    db.BulkUpdate(memberShips);
                }
            }

            db.BulkUpdate(updateMembers);
            db = new SwgohDb();

            db.BulkInsert(newMembers);
            db = new SwgohDb();

            db.BulkInsert(memberCharactersAdd);
            db = new SwgohDb();

            db.BulkInsert(memberShipsAdd);
            db = new SwgohDb();

            var guildUpdate = db.Guilds.Find(id);
            var powers      = db.Members.Where(x => x.Guild_Id == id).ToList();

            guildUpdate.CharacterPower = powers.Sum(x => x.CharacterPower);
            guildUpdate.ShipPower      = powers.Sum(x => x.ShipPower);

            db.Entry(guildUpdate).State = EntityState.Modified;
            db.SaveChanges();
        }