public SolarSystem AssignExplorationTargetORIG(Ship queryingShip)
 {
     List<SolarSystem> Potentials = new List<SolarSystem>();
     foreach (SolarSystem s in UniverseScreen.SolarSystemList)
     {
         if (s.ExploredDict[this.empire])
         {
             continue;
         }
         Potentials.Add(s);
     }
     foreach (SolarSystem s in this.MarkedForExploration)
     {
         Potentials.Remove(s);
     }
     IOrderedEnumerable<SolarSystem> sortedList =
         from system in Potentials
         orderby Vector2.Distance(this.empire.GetWeightedCenter(), system.Position)
         select system;
     if (sortedList.Count<SolarSystem>() <= 0)
     {
         queryingShip.GetAI().OrderQueue.Clear();
         return null;
     }
     this.MarkedForExploration.Add(sortedList.First<SolarSystem>());
     return sortedList.First<SolarSystem>();
 }
        public void AssignShipToForce(Ship toAdd)
        {
            int numWars = 0;
            foreach (KeyValuePair<Empire, Ship_Game.Gameplay.Relationship> Relationship in this.empire.GetRelations())
            {
                if (!Relationship.Value.AtWar || Relationship.Key.isFaction)
                {
                    continue;
                }
                numWars++;
            }
            float baseDefensePct = 0.1f;
            baseDefensePct = baseDefensePct + 0.15f * (float)numWars;
            float defStr = this.DefensiveCoordinator.GetForcePoolStrength();

            if (baseDefensePct > 0.35f)
            {
                baseDefensePct = 0.35f;
            }
            float EntireStrength = 0f;
            foreach (Ship ship in this.empire.GetShips())
            {
                EntireStrength = EntireStrength + ship.GetStrength();
            }
            //added by gremlin dont add zero strength ships to defensive force pool
            //if (this.DefensiveCoordinator.GetForcePoolStrength() / EntireStrength <= baseDefensePct
            if ((this.DefensiveCoordinator.defenseDeficit > 0  && this.DefensiveCoordinator.GetForcePoolStrength() < EntireStrength * baseDefensePct)
                && (toAdd.BombBays.Count == 0 || toAdd.WarpThrust <= 0f) &&toAdd.GetStrength()>0 && toAdd.BaseCanWarp)  //
            {
                this.DefensiveCoordinator.DefensiveForcePool.Add(toAdd);
                toAdd.GetAI().SystemToDefend = null;
                toAdd.GetAI().SystemToDefendGuid = Guid.Empty;
                toAdd.GetAI().HasPriorityOrder = false;
                toAdd.GetAI().State = AIState.SystemDefender;
                this.DefensiveCoordinator.defenseDeficit-=toAdd.BaseStrength;
                return;
            }
            IOrderedEnumerable<AO> sorted =
                from ao in this.empire.GetGSAI().AreasOfOperations
                orderby Vector2.Distance(toAdd.Position, ao.Position)
                select ao;
            if (sorted.Count<AO>() <= 0)
            {
                this.empire.GetForcePool().Add(toAdd);
                return;
            }
            //sorted.First().AddShip(toAdd);//   First<AO>().AddShip(toAdd);
            sorted.ElementAt(0).AddShip(toAdd);
        }
        //added by gremlin ExplorationTarget
        public SolarSystem AssignExplorationTarget(Ship queryingShip)
        {
            List<SolarSystem> Potentials = new List<SolarSystem>();
            foreach (SolarSystem s in UniverseScreen.SolarSystemList)
            {
                if (s.ExploredDict[this.empire])
                {
                    continue;
                }
                Potentials.Add(s);
            }
            this.MarkedForExploration.thisLock.EnterReadLock();
            foreach (SolarSystem s in this.MarkedForExploration)
            {
                Potentials.Remove(s);
            }
            this.MarkedForExploration.thisLock.ExitReadLock();
            IOrderedEnumerable<SolarSystem> sortedList =
                from system in Potentials
                orderby Vector2.Distance(this.empire.GetWeightedCenter(), system.Position)
                select system;
            if (sortedList.Count<SolarSystem>() <= 0)
            {
                queryingShip.GetAI().OrderQueue.Clear();
                return null;
            }
            //SolarSystem nearesttoScout = sortedList.OrderBy(furthest => Vector2.Distance(queryingShip.Center, furthest.Position)).FirstOrDefault();
            SolarSystem nearesttoHome = sortedList.OrderBy(furthest => Vector2.Distance(this.empire.GetWeightedCenter(), furthest.Position)).FirstOrDefault(); ;
            //SolarSystem potentialTarget = null;
            foreach (SolarSystem nearest in sortedList)
            {
                if (nearest.CombatInSystem) continue;
                float distanceToScout = Vector2.Distance(queryingShip.Center, nearest.Position);
                float distanceToEarth = Vector2.Distance(this.empire.GetWeightedCenter(), nearest.Position);

                if (distanceToScout > distanceToEarth + 50000f)
                {
                    continue;
                }
                nearesttoHome = nearest;
                break;

            }
            this.MarkedForExploration.Add(nearesttoHome);
            return nearesttoHome;
        }
        //Added by McShooterz: for refit to keep name
        public static Ship CreateShipAt(string key, Empire Owner, Planet p, bool DoOrbit, string RefitName, byte RefitLevel)
        {
            Ship newShip;
            //if (universeScreen.MasterShipList.pendingRemovals.TryPop(out newShip))
            //{
            //    newShip.ShipRecreate();
            //    newShip.Role = Ship_Game.ResourceManager.ShipsDict[key].Role;
            //    newShip.Name = Ship_Game.ResourceManager.ShipsDict[key].Name;
            //    newShip.BaseStrength = Ship_Game.ResourceManager.ShipsDict[key].BaseStrength;
            //    newShip.BaseCanWarp = Ship_Game.ResourceManager.ShipsDict[key].BaseCanWarp;
            //}
            //else
            newShip = new Ship()
            {
                Role = Ship_Game.ResourceManager.ShipsDict[key].Role,
                Name = Ship_Game.ResourceManager.ShipsDict[key].Name,
                BaseStrength = Ship_Game.ResourceManager.ShipsDict[key].BaseStrength,
                BaseCanWarp = Ship_Game.ResourceManager.ShipsDict[key].BaseCanWarp

            };
            newShip.LoadContent(GetContentManager());
            SceneObject newSO = new SceneObject();
            if (!Ship_Game.ResourceManager.ShipsDict[key].GetShipData().Animated)
            {
                newSO = new SceneObject(Ship_Game.ResourceManager.GetModel(Ship_Game.ResourceManager.ShipsDict[key].ModelPath).Meshes[0])
                {
                    ObjectType = ObjectType.Dynamic
                };
                newShip.SetSO(newSO);
            }
            else
            {
                SkinnedModel model = Ship_Game.ResourceManager.GetSkinnedModel(Ship_Game.ResourceManager.ShipsDict[key].ModelPath);
                newSO = new SceneObject(model.Model);
                newShip.SetAnimationController(new AnimationController(model.SkeletonBones), model);
            }
            newSO.ObjectType = ObjectType.Dynamic;
            newShip.SetSO(newSO);
            foreach (Thruster t in Ship_Game.ResourceManager.ShipsDict[key].GetTList())
            {
                Thruster thr = new Thruster()
                {
                    Parent = newShip,
                    tscale = t.tscale,
                    XMLPos = t.XMLPos
                };
                newShip.GetTList().Add(thr);
            }
            foreach (ModuleSlot slot in Ship_Game.ResourceManager.ShipsDict[key].ModuleSlotList)
            {
                ModuleSlot newSlot = new ModuleSlot();
                newSlot.SetParent(newShip);
                newSlot.SlotOptions = slot.SlotOptions;
                newSlot.Restrictions = slot.Restrictions;
                newSlot.Position = slot.Position;
                newSlot.facing = slot.facing;
                newSlot.state = slot.state;
                newSlot.InstalledModuleUID = slot.InstalledModuleUID;
                newShip.ModuleSlotList.AddLast(newSlot);
            }
            newShip.Position = p.Position;
            newShip.loyalty = Owner;

            newShip.Initialize();
            //Added by McShooterz: add automatic ship naming
            newShip.VanityName = RefitName;
            newShip.Level = RefitLevel;
            newShip.GetSO().World = Matrix.CreateTranslation(new Vector3(newShip.Center, 0f));
            lock (GlobalStats.ObjectManagerLocker)
            {
                Ship_Game.ResourceManager.universeScreen.ScreenManager.inter.ObjectManager.Submit(newShip.GetSO());
            }
            foreach (Thruster t in newShip.GetTList())
            {
                t.load_and_assign_effects(Ship_Game.ResourceManager.universeScreen.ScreenManager.Content, "Effects/ThrustCylinderB", "Effects/NoiseVolume", Ship_Game.ResourceManager.universeScreen.ThrusterEffect);
                t.InitializeForViewing();
            }
            if (newShip.Role == "fighter")
            {
                Ship level = newShip;
                level.Level += Owner.data.BonusFighterLevels;
            }
            Owner.AddShip(newShip);
            newShip.GetAI().State = AIState.AwaitingOrders;
            return newShip;
        }
        public static string GetStatusText(Ship ship)
        {
            string which;
            string str;
            string text = "";
            switch (ship.GetAI().State)
            {
                case AIState.DoNothing:
                {
                    text = Localizer.Token(183);
                    break;
                }
                case AIState.Combat:
                {
                    if (ship.GetAI().Intercepting)
                    {
                        if (ship.GetAI().Target == null)
                        {
                            break;
                        }
                        text = string.Concat(Localizer.Token(157), " ", (ship.GetAI().Target as Ship).VanityName);
                        break;
                    }
                    else if (ship.GetAI().Target == null)
                    {
                        text = Localizer.Token(155);
                        text = string.Concat(text, "\n", Localizer.Token(156));
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(158), " ", (ship.GetAI().Target as Ship).loyalty.data.Traits.Name);
                        break;
                    }
                }
                case AIState.HoldPosition:
                {
                    text = Localizer.Token(180);
                    break;
                }
                case AIState.ManualControl:
                {
                    text = Localizer.Token(171);
                    break;
                }
                case AIState.AwaitingOrders:
                {
                    return Localizer.Token(153);
                }
                case AIState.AttackTarget:
                {
                    if (ship.GetAI().Target == null)
                    {
                        text = Localizer.Token(155);
                        text = string.Concat(text, "\n", Localizer.Token(156));
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(154), " ", (ship.GetAI().Target as Ship).VanityName);
                        break;
                    }
                }
                case AIState.Escort:
                {
                    if (ship.GetAI().EscortTarget == null)
                    {
                        break;
                    }
                    text = string.Concat(Localizer.Token(179), " ", ship.GetAI().EscortTarget.Name);
                    break;
                }
                case AIState.SystemTrader:
                {
                    if (ship.GetAI().OrderQueue.Count <= 0)
                    {
                        text = string.Concat(Localizer.Token(164), "\n", Localizer.Token(165));
                        break;
                    }
                    else
                    {
                        switch (ship.GetAI().OrderQueue.Last.Value.Plan)
                        {
                            case ArtificialIntelligence.Plan.PickupGoods:
                            {
                                which = ship.GetAI().FoodOrProd;
                                if (which == "Prod")
                                {
                                    which = "Production";
                                }
                                text = string.Concat(text, Localizer.Token(159), " ", ship.GetAI().start.Name);
                                string pickingup = Localizer.Token(160);
                                string str1 = text;
                                string[] strArrays = new string[] { str1, "\n", pickingup, " ", null };
                                strArrays[4] = (which == "Food" ? Localizer.Token(161) : Localizer.Token(162));
                                text = string.Concat(strArrays);
                                break;
                            }
                            case ArtificialIntelligence.Plan.DropOffGoods:
                            {
                                which = ship.GetAI().FoodOrProd;
                                if (which == "Prod")
                                {
                                    which = "Production";
                                }
                                text = string.Concat(text, Localizer.Token(159), " ", ship.GetAI().end.Name);
                                string delivering = Localizer.Token(163);
                                string str2 = text;
                                string[] strArrays1 = new string[] { str2, "\n", delivering, " ", null };
                                strArrays1[4] = (which == "Food" ? Localizer.Token(161) : Localizer.Token(162));
                                text = string.Concat(strArrays1);
                                break;
                            }
                        }
                    }
                    break;
                }
                case AIState.AttackRunner:
                case AIState.PatrolSystem:
                case AIState.Flee:

                {
                    if (ship.GetAI().OrbitTarget == null)
                    {
                        text = Localizer.Token(182);
                        break;
                    }
                    else
                    {
                        text = string.Concat("Fleeing to", " ", ship.GetAI().OrbitTarget.Name);
                        break;
                    }
                }
                case AIState.PirateRaiderCarrier:
                case AIState.AwaitingOffenseOrders:
                case AIState.MineAsteroids:
                case AIState.Intercept:
                case AIState.AssaultPlanet:
                case AIState.Exterminate:
                {
                    if (ship.GetAI().OrderQueue.Count <= 0)
                    {
                        text = ship.GetAI().State.ToString();
                        break;
                    }
                    else
                    {
                        if (ship.GetAI().OrderQueue.First.Value.TargetPlanet == null)  //fbedard
                            text = ship.GetAI().OrderQueue.First.Value.Plan.ToString();
                        else
                            //text = ship.GetAI().OrderQueue.First.Value.Plan.ToString();
                            text = string.Concat(ship.GetAI().OrderQueue.First.Value.Plan.ToString(), " to ", ship.GetAI().OrderQueue.First.Value.TargetPlanet.Name);
                        break;
                    }
                }
                case AIState.Orbit:
                {
                    if (ship.GetAI().OrbitTarget == null)
                    {
                        text = Localizer.Token(182);
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(182), " ", ship.GetAI().OrbitTarget.Name);
                        break;
                    }
                }
                case AIState.PassengerTransport:
                {
                    if (ship.GetAI().OrderQueue.Count <= 0)
                    {
                        text = string.Concat(Localizer.Token(168), "\n", Localizer.Token(165));
                        break;
                    }
                    else
                    {
                        try
                        {
                            switch (ship.GetAI().OrderQueue.Last.Value.Plan)
                            {
                                case ArtificialIntelligence.Plan.PickupPassengers:
                                {
                                    text = string.Concat(text, Localizer.Token(159), " ", ship.GetAI().start.Name);
                                    text = string.Concat(text, "\n", Localizer.Token(166));
                                    break;
                                }
                                case ArtificialIntelligence.Plan.DropoffPassengers:
                                {
                                    text = string.Concat(text, Localizer.Token(159), " ", ship.GetAI().end.Name);
                                    text = string.Concat(text, "\n", Localizer.Token(167));
                                    break;
                                }
                            }
                            break;
                        }
                        catch
                        {
                            str = "";
                        }
                        return str;
                    }
                }
                case AIState.Colonize:
                {
                    if (ship.GetAI().ColonizeTarget == null)
                    {
                        break;
                    }
                    text = string.Concat(Localizer.Token(169), " ", ship.GetAI().ColonizeTarget.Name);
                    break;
                }
                case AIState.MoveTo:
                {
                    if (!(ship.Velocity == Vector2.Zero) || ship.isTurning)
                    {
                        text = string.Concat(Localizer.Token(187), " ");
                        if (ship.GetAI().OrderQueue.Count <= 0)
                        {
                            IOrderedEnumerable<SolarSystem> sortedList =
                                from system in UniverseScreen.SolarSystemList
                                orderby Vector2.Distance(ship.GetAI().MovePosition, system.Position)
                                select system;
                            text = string.Concat(text, Localizer.Token(189), " ", sortedList.First<SolarSystem>().Name);
                            if (sortedList.First<SolarSystem>().ExploredDict[EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)])
                            {
                                break;
                            }
                            text = Localizer.Token(174);
                            break;
                        }
                        else if (ship.GetAI().OrderQueue.Last.Value.Plan != ArtificialIntelligence.Plan.DeployStructure)
                        {
                            IOrderedEnumerable<SolarSystem> sortedList =
                                from system in UniverseScreen.SolarSystemList
                                orderby Vector2.Distance(ship.GetAI().MovePosition, system.Position)
                                select system;
                            text = string.Concat(text, sortedList.First<SolarSystem>().Name);
                            if (sortedList.First<SolarSystem>().ExploredDict[EmpireManager.GetEmpireByName(Ship.universeScreen.PlayerLoyalty)])
                            {
                                break;
                            }
                            text = Localizer.Token(174);
                            break;
                        }
                        else
                        {
                            text = string.Concat(text, Localizer.Token(188), " ", ResourceManager.ShipsDict[ship.GetAI().OrderQueue.Last.Value.goal.ToBuildUID].Name);
                            break;
                        }
                    }
                    else
                    {
                        text = Localizer.Token(180);
                        break;
                    }
                }
                case AIState.Explore:
                {
                    text = Localizer.Token(174);
                    break;
                }
                case AIState.SystemDefender:
                {
                    text = Localizer.Token(170);
                    break;
                }
                case AIState.Resupply:
                {
                    if (ship.GetAI().resupplyTarget == null)
                    {
                        text = Localizer.Token(173);
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(172), " ", ship.GetAI().resupplyTarget.Name);
                        break;
                    }
                }
                case AIState.Rebase:
                {
                    //text = Localizer.Token(178);
                    text = string.Concat(Localizer.Token(178), " to ", ship.GetAI().OrderQueue.Last.Value.TargetPlanet.Name);  //fbedard
                    break;
                }
                case AIState.Bombard:
                {
                    if (ship.GetAI().OrderQueue.Count <= 0 || ship.GetAI().OrderQueue.First.Value.TargetPlanet == null)
                    {
                        break;
                    }
                    if (Vector2.Distance(ship.Center, ship.GetAI().OrderQueue.First.Value.TargetPlanet.Position) >= 2500f)
                    {
                        text = string.Concat(Localizer.Token(176), " ", ship.GetAI().OrderQueue.First.Value.TargetPlanet.Name);
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(175), " ", ship.GetAI().OrderQueue.First.Value.TargetPlanet.Name);
                        break;
                    }
                }
                case AIState.BombardTroops:
                {
                    if (ship.GetAI().OrderQueue.Count <= 0 || ship.GetAI().OrderQueue.First.Value.TargetPlanet == null)
                    {
                        break;
                    }
                    if (Vector2.Distance(ship.Center, ship.GetAI().OrderQueue.First.Value.TargetPlanet.Position) >= 2500f)
                    {
                        text = string.Concat("Soften", " ", ship.GetAI().OrderQueue.First.Value.TargetPlanet.Name);
                        break;
                    }
                    else
                    {
                        text = string.Concat(Localizer.Token(175), " ", ship.GetAI().OrderQueue.First.Value.TargetPlanet.Name);
                        break;
                    }
                }
                case AIState.Boarding:
                {
                    text = Localizer.Token(177);
                    break;
                }
                case AIState.ReturnToHangar:
                {
                    text = Localizer.Token(181);
                    break;
                }
                case AIState.Ferrying:
                {
                    text = Localizer.Token(185);
                    break;
                }
                case AIState.Refit:
                {
                    text = Localizer.Token(184);
                    break;
                }
                case AIState.Scrap:
                {
                    text = Localizer.Token(186);
                    break;
                }
                case AIState.FormationWarp:
                {
                    text = "Moving in Formation";
                    break;
                }
                case AIState.Scuttle:
                {
                    text = string.Concat("Self Destruct: ", ship.ScuttleTimer.ToString("#"));
                    break;
                }
                default:
                {
                    goto case AIState.Exterminate;
                }
            }
            return text;
        }
        //added by gremlin replace redundant code with method
        private void RightClickship(Ship ship, Planet planet, bool audio)
        {
            if (ship.Role == "construction")
            {
                if(audio)
                    AudioManager.PlayCue("UI_Misc20");
                return;
            }
            else
            {
                if(audio)
                    AudioManager.PlayCue("echo_affirm1");
                if (ship.isColonyShip)
                {
                    if (planet.Owner == null && planet.habitable)
                        ship.GetAI().OrderColonization(planet);
                    else
                        ship.GetAI().OrderToOrbit(planet, true);
                }
                else if (ship.Role == "troop" || (ship.TroopList.Count > 0 && (ship.HasTroopBay || ship.hasTransporter)))
                {
                    if (planet.Owner != null && planet.Owner == this.player && (!ship.HasTroopBay && !ship.hasTransporter))
                    {
                        if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                            ship.GetAI().OrderToOrbit(planet, false);
                        else
                            ship.GetAI().OrderRebase(planet, true);
                    }
                    else
                        //add new right click troop and troop ship options on planets
                        if (planet.habitable && (planet.Owner == null || planet.Owner != this.player && (ship.loyalty.GetRelations()[planet.Owner].AtWar || planet.Owner.isFaction || planet.Owner.data.Defeated || planet.Owner == null)))
                        {
                            if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                ship.GetAI().OrderToOrbit(planet, false);
                            else
                            {

                                ship.GetAI().State = AIState.AssaultPlanet;
                                ship.GetAI().OrderLandAllTroops(planet);
                            }
                        }

                        else
                        {

                            ship.GetAI().OrderOrbitPlanet(planet);// OrderRebase(planet, true);
                        }
                }
                else if (ship.BombBays.Count > 0)
                {
                    float enemies = planet.GetGroundStrengthOther(this.player) * 1.5f;
                    float friendlies = planet.GetGroundStrength(this.player);
                    if (planet.Owner != this.player)
                    {
                        if (planet.Owner == null || this.player.GetRelations()[planet.Owner].AtWar || planet.Owner.isFaction || planet.Owner.data.Defeated)
                        {
                            if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                                ship.GetAI().OrderBombardPlanet(planet);
                            else if (enemies > friendlies || planet.Population > 0f)
                                ship.GetAI().OrderBombardPlanet(planet);
                            else
                            {
                                ship.GetAI().OrderToOrbit(planet, false);
                            }
                        }
                        else
                        {
                            ship.GetAI().OrderToOrbit(planet, false);
                        }

                    }
                    else if (enemies > friendlies && input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                    {
                        ship.GetAI().OrderBombardPlanet(planet);
                    }
                    else
                        ship.GetAI().OrderToOrbit(planet, true);
                }
                else if (input.CurrentKeyboardState.IsKeyDown(Keys.LeftShift))
                    ship.GetAI().OrderToOrbit(planet, false);
                else
                    ship.GetAI().OrderToOrbit(planet, true);
            }
        }
        public void AddShip(Ship ship)
        {
            if (ship.BaseStrength == 0)
                return;

            if (this.ThreatLevel <
                this.CoreFleet.GetStrength())
            {
                this.OffensiveForcePool.Add(ship);
                this.Flip = !this.Flip;
                return;
            }
            if (this.CoreFleet.Task == null && ship.fleet == null)
            {
                ship.GetAI().OrderQueue.Clear();
                ship.GetAI().HasPriorityOrder = false;
                this.CoreFleet.AddShip(ship);
                foreach (Ship waiting in this.ShipsWaitingForCoreFleet)
                {
                    if (waiting.fleet != null)
                    {
                        continue;
                    }
                    this.CoreFleet.AddShip(waiting);
                    waiting.GetAI().OrderQueue.Clear();
                    waiting.GetAI().HasPriorityOrder = false;
                }
                this.CoreFleet.Position = this.CoreWorld.Position;
                this.CoreFleet.AutoArrange();
                this.CoreFleet.MoveToNow(this.Position, 0f, new Vector2(0f, -1f));
                this.ShipsWaitingForCoreFleet.Clear();
            }
            else if (ship.fleet == null)
            {
                this.ShipsWaitingForCoreFleet.Add(ship);
                this.OffensiveForcePool.Add(ship);
            }
            this.Flip = !this.Flip;
        }