Source

EmergencyRecover / EmergencyRecover / EmergencyRecover / Core.cs

Full commit
using GTA;

namespace EmergencyRecover
{
   public class Core : Script
   {
      private static readonly object SyncLock = new object();
      private readonly KeyHandling _keyHandling;

      public Core()
      {
         _keyHandling = new KeyHandling(this);
         KeyDown += OneyKeyDown;
      }

      private void OneyKeyDown(object sender, KeyEventArgs e)
      {
         Configuration = new ConfigurationHandling().ReadConfig();
         if (Configuration == null)
            CommonFunctions.DisplayText("Configuration could not be read!", 3000);
         _keyHandling.HandleKey(e);
      }

      internal ConfigurationContainer Configuration { get; set; }

      public void Recover()
      {
         lock (SyncLock)
         {
            var actualPosition = Player.Character.Position;
            foreach (var ped in World.GetPeds(actualPosition, 5.0f))
            {
               if (ReferenceEquals(Player.Character, ped))
                  continue;
               ped.FreezePosition = false;
               ClearTasksIfRequested(ped);
               DeletePedIfRequested(ped);
            }
            foreach (var vehicle in World.GetVehicles(actualPosition, 5.0f))
            {
               vehicle.FreezePosition = false;
               UnlockVehicleIfRequested(vehicle);
               DeleteVehicleIfRequested(vehicle);
            }
            CommonFunctions.DisplayText("Emergency recovery done.", 4000);
         }
      }

      private bool AffectPlayerVehicleIfRequested(Vehicle vehicle)
      {
         if (!Configuration.AffectPlayerVehicle && ReferenceEquals(Player.LastVehicle, vehicle))
            return false;
         return true;
      }

      private void ClearTasksIfRequested(Ped ped)
      {
         if (!Configuration.ClearTasks)
            return;
         ped.isRequiredForMission = false;
         ped.Task.ClearAllImmediately();
         ped.NoLongerNeeded();
      }

      private void DeletePedIfRequested(Ped ped)
      {
         if (!Configuration.DeletePeds)
            return;
         if (!CommonFunctions.PedExists(ped))
            return;
         ped.NoLongerNeeded();
         ped.Delete();
      }

      private void DeleteVehicleIfRequested(Vehicle vehicle)
      {
         if (!Configuration.DeleteVehicles)
            return;
         if (!CommonFunctions.VehicleExists(vehicle))
            return;
         if (AffectPlayerVehicleIfRequested(vehicle))
            vehicle.Delete();
      }

      private void UnlockVehicleIfRequested(Vehicle vehicle)
      {
         if (!Configuration.UnlockVehicles)
            return;
         if (!CommonFunctions.VehicleExists(vehicle))
            return;
         if (AffectPlayerVehicleIfRequested(vehicle))
         {
            vehicle.NoLongerNeeded();
            vehicle.DoorLock = DoorLock.None;
         }
      }
   }
}