context: using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Threading.Tasks;
  using PokemonGo.RocketAPI.Enums;
  using PokemonGo.RocketAPI.Extensions;
  using PokemonGo.RocketAPI.Logic.Utils;
  using PokemonGo.RocketAPI.Exceptions;
  using System.Net;
  using System.IO;
  using System.Device.Location;
  using PokemonGo.RocketAPI.Helpers;
  using System.Web.Script.Serialization;
  using POGOProtos.Map.Pokemon;
  using POGOProtos.Inventory.Item;
  using POGOProtos.Enums;
  using POGOProtos.Networking.Responses;
  using POGOProtos.Map.Fort;
  using POGOProtos.Data;
  using System.Threading;
  using POGOProtos.Inventory;
  using Newtonsoft.Json;
  using GoogleMapsApi;
  using GoogleMapsApi.Entities.Common;
  using GoogleMapsApi.Entities.Directions.Request;
  using GoogleMapsApi.Entities.Directions.Response;
  using GoogleMapsApi.Entities.Geocoding.Request;
  using GoogleMapsApi.Entities.Geocoding.Response;
  using GoogleMapsApi.StaticMaps;
  using GoogleMapsApi.StaticMaps.Entities;
  using PokemonGo.RocketApi.PokeMap;
  using System.Reflection;
  using System.Windows.Forms;
  using System.Diagnostics;
  
  namespace PokemonGo.RocketAPI.Logic
  {
      public class Logic
      {
          #region Define Session Variables
          public static Client _client;
          public readonly ISettings _clientSettings;
          public TelegramUtil _telegram;
          public BotStats _botStats;
          private readonly Navigation _navigation;
          public const double SpeedDownTo = 10 / 3.6;
          private readonly LogicInfoObservable _infoObservable;
          private readonly PokeVisionUtil _pokevision;
          private int pokemonCatchCount;
          private int pokeStopFarmedCount;
          private double timetorunstamp = -10000;
          private double pausetimestamp = -10000;
          private double resumetimestamp = -10000;
          private double startingXP = -10000;
          private double currentxp = -10000;
          private bool havelures = false;
          private bool pokeballoutofstock = false;
          private bool stopsloaded = false;
          private bool gymsloaded = false;
          public static Logic _instance;
          private bool _pauseWalking = false;
          private int count = 0;
          public static int failed_softban = 0;
          int level = -1;
          public bool pauseWalking
          {
              get
              {
                  if (_navigation != null)
                  {
                      _pauseWalking = _navigation.pauseWalking;
                  }
                  return _pauseWalking;
              }
              set
              {
                  if (_navigation != null)
                  {
                      _navigation.pauseWalking = value;
                      _pauseWalking = value;
                  }
              }
          }
  
          public Logic(ISettings clientSettings, LogicInfoObservable infoObservable)
          {
              _clientSettings = clientSettings;
              _client = new Client(_clientSettings);
              _client.setFailure(new ApiFailureStrat(_client));
              _botStats = new BotStats();
              _navigation = new Navigation(_client);
              _pokevision = new PokeVisionUtil();
              _infoObservable = infoObservable;
              _instance = this;
          }
  
          #endregion
  
          #region Execute Functions
  
          public async Task Execute()
          {
  
              // Check if disabled
              StringUtils.CheckKillSwitch();
              await SetCheckTimeToRun();
              for (int i = 0; i < 10; i++)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Red, "Don't login with the new App Version (0.3.7) (0.3.5 is ok!), or you will probably get Banned if you use the bot again after that!");
              }
              Logger.ColoredConsoleWrite(ConsoleColor.Red, "This bot is absolutely free and open-source!");
              Logger.ColoredConsoleWrite(ConsoleColor.Red, "If you've paid for it. Request a chargeback immediately!");
              Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Starting Execute on login server: {_clientSettings.AuthType}", LogLevel.Info);
              if (_clientSettings.logPokemons)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Green, "You enabled Pokemonlogging. It will be saved to \"\\Logs\\PokeLog.txt\"");
              }
              if (_clientSettings.logManualTransfer)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Green, "You enabled manual transfer logging. It will be saved to \"\\Logs\\TransferLog.txt\"");
              }
              if (_clientSettings.bLogEvolve)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Green, "You enabled Evolution Logging. It will be saved to \"\\Logs\\EvolutionLog.txt\"");
              }
              Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Setting Pokemon Catch Count: to 0 for this session", LogLevel.Info);
              pokemonCatchCount = 0;
              Logger.ColoredConsoleWrite(ConsoleColor.Green, $"Setting Pokestop Farmed Count to 0 for this session", LogLevel.Info);
              pokeStopFarmedCount = 0;
              _client.CurrentAltitude = _client.Settings.DefaultAltitude;
              _client.CurrentLongitude = _client.Settings.DefaultLongitude;
              _client.CurrentLatitude = _client.Settings.DefaultLatitude;
  
              if (_client.CurrentAltitude == 0)
              {
                  _client.CurrentAltitude = LocationUtils.getAltidude(_client.CurrentLatitude, _client.CurrentLongitude);
                  Logger.Error("Altidude was 0, resolved that. New Altidude is now: " + _client.CurrentAltitude);
              }
  
              if (_clientSettings.UseProxyVerified)
              {
                  Logger.Error("===============================================");
                  Logger.Error("Proxy enabled.");
                  Logger.Error("ProxyIP: " + _clientSettings.UseProxyHost + ":" + _clientSettings.UseProxyPort);
                  Logger.Error("===============================================");
              }
  
              while (true)
              {
                  try
                  {
                      await _client.Login.DoLogin();
  
                      if (!string.IsNullOrEmpty(_clientSettings.TelegramAPIToken) && !string.IsNullOrEmpty(_clientSettings.TelegramName))
                      {
                          try
                          {
                              _telegram = new TelegramUtil(_client, new Telegram.Bot.TelegramBotClient(_clientSettings.TelegramAPIToken), _clientSettings, _client.Inventory);
  
                              Logger.ColoredConsoleWrite(ConsoleColor.Green, "To activate informations with Telegram, write the bot a message for more informations");
                              var me = await _telegram.getClient().GetMeAsync();
                              _telegram.getClient().OnCallbackQuery += _telegram.BotOnCallbackQueryReceived;
                              _telegram.getClient().OnMessage += _telegram.BotOnMessageReceived;
                              _telegram.getClient().OnMessageEdited += _telegram.BotOnMessageReceived;
                              Logger.ColoredConsoleWrite(ConsoleColor.Green, "Telegram Name: " + me.Username);
                              _telegram.getClient().StartReceiving();
                          }
                          catch (Exception) { }
                      }
  
                      await PostLoginExecute();
                  }
                  catch (Exception ex)
                  {
                      Logger.Error($"Error: " + ex.Source);
                      Logger.Error($"{ex}");
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Trying to Restart.");
                      try
                      {
                          _telegram.getClient().StopReceiving();
                      }
                      catch (Exception) { }
                  }
  
                  Logger.ColoredConsoleWrite(ConsoleColor.Red, "Restarting in 10 Seconds.");
                  await Task.Delay(10000);
              }
          }
  
          public async Task PostLoginExecute()
          {
              while (true)
              {
                  var _restart = true;
                  try
                  {
                      var profil = await _client.Player.GetPlayer();
                      await _client.Inventory.ExportPokemonToCSV(profil.PlayerData);
                      await StatsLog(_client);
  
                      if (_clientSettings.EvolvePokemonsIfEnoughCandy)
                      {
                          await EvolveAllPokemonWithEnoughCandy();
                      }
  
                      if (_clientSettings.AutoIncubate)
                      {
                          await StartIncubation();
                      }
  
                      await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve, _clientSettings.TransferFirstLowIV);
                      //await RecycleItems();
                      await ExecuteFarmingPokestopsAndPokemons(_client);
                  }
                  catch (AccessTokenExpiredException)
                  {
                      throw new AccessTokenExpiredException();
                  }
                  catch (Exception ex)
                  {
                      Logger.Write($"Exception: {ex}", LogLevel.Error);
                      if (ex.ToString().Contains("Time To Run Reached"))
                      {
                          _restart = false;
                      }
                  }
                  if (_restart)
                  {
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Starting again in 60 seconds...");
                      await Task.Delay(60000);
                  }
                  else
                  {
                      throw new Exception("Time To Run Reached");
                  }
              }
          }
  
          #endregion
  
          #region Update Functions
  
          public static Version getNewestVersion()
          {
              try
              {
                  var match = DownloadServerVersion();
  
                  var gitVersion = new Version(match);
  
                  return gitVersion;
  
              }
              catch (Exception)
              {
                  return Assembly.GetExecutingAssembly().GetName().Version;
              }
          }
  
          public static string DownloadServerVersion()
          {
              using (var wC = new WebClient())
                  return
                      wC.DownloadString(
                          "https://raw.githubusercontent.com/Ar1i/PokemonGo-Bot/master/ver.md");
          }
  
          #endregion
  
          #region Stats log and Session Check Functions
  
          private async Task StatsLog(Client client)
          {
              //
              _client.readyToUse = true;  // Enable Pokemon List cause everything is loaded
  
              // Check if disabled
              StringUtils.CheckKillSwitch();
              await SetCheckTimeToRun();
              var profile = await _client.Player.GetPlayer();
              var playerStats = await _client.Inventory.GetPlayerStats();
              var stats = playerStats.First();
  
              var expneeded = stats.NextLevelXp - stats.PrevLevelXp - StringUtils.getExpDiff(stats.Level);
              var curexp = stats.Experience - stats.PrevLevelXp - StringUtils.getExpDiff(stats.Level);
              var curexppercent = Convert.ToDouble(curexp) / Convert.ToDouble(expneeded) * 100;
              if (startingXP == -10000) startingXP = stats.Experience;
              currentxp = stats.Experience;
              var pokemonToEvolve = (await _client.Inventory.GetPokemonToEvolve()).Count();
              var pokedexpercentraw = Convert.ToDouble(stats.UniquePokedexEntries) / Convert.ToDouble(150) * 100;
              var pokedexpercent = Math.Floor(pokedexpercentraw);
  
              if (curexp == 0 && expneeded == 1000)
              {
                  // Do Tutorial
                  await _client.Misc.MarkTutorialComplete();
              }
              var items = await _client.Inventory.GetItems();
              var pokeBallCollection = await GetPokeballQty();
  
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "-----------------------[PLAYER STATS]-----------------------");
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, $"Level/EXP: {stats.Level} | {curexp.ToString("N0")}/{expneeded.ToString("N0")} ({Math.Round(curexppercent, 2)}%)");
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "EXP to Level up: " + (stats.NextLevelXp - stats.Experience)); ;
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "PokeStops visited: " + stats.PokeStopVisits);
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "KM Walked: " + Math.Round(stats.KmWalked, 2));
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Pokemon: " + await _client.Inventory.getPokemonCount() + " + " + await _client.Inventory.GetEggsCount() + " Eggs /" + profile.PlayerData.MaxPokemonStorage + " (" + pokemonToEvolve + " Evolvable)");
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Pokedex Completion: " + stats.UniquePokedexEntries + "/150 " + "[" + pokedexpercent + "%]");
              //Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Items: " + await _client.Inventory.getInventoryCount() + "/" + profile.PlayerData.MaxItemStorage);
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Stardust: " + profile.PlayerData.Currencies.ToArray()[1].Amount.ToString("N0"));
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "------------------------------------------------------------");
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Pokemon Catch Count this session: " + pokemonCatchCount);
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "PokeStop Farmed Count this session: " + pokeStopFarmedCount);
              //foreach (KeyValuePair<string, int> pokeballtype in pokeBallCollection)
              //{
              //    Logger.ColoredConsoleWrite(ConsoleColor.Cyan, pokeballtype.Key + " Qty: " + pokeballtype.Value.ToString());
              //}
              var totalitems = 0;
              foreach (var item in items)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Cyan, item.ItemId + " Qty: " + item.Count);
                  totalitems += item.Count;
                  if (item.ItemId == ItemId.ItemTroyDisk && item.Count > 0)
                  {
                      havelures = true;
                  }
              }
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "Items: " + totalitems + "/" + profile.PlayerData.MaxItemStorage);
              Logger.ColoredConsoleWrite(ConsoleColor.Cyan, "------------------------------------------------------------");
              if (level == -1)
              {
                  level = stats.Level;
              }
              else if (stats.Level > level)
              {
                  level = stats.Level;
                  Logger.ColoredConsoleWrite(ConsoleColor.Magenta, "Got the level up reward from your level up.");
                  var lvlup = await _client.Player.GetLevelUpRewards(stats.Level);
                  List<ItemId> alreadygot = new List<ItemId>();
                  foreach (var i in lvlup.ItemsAwarded)
                  {
                      if (!alreadygot.Contains(i.ItemId))
                      {
                          Logger.ColoredConsoleWrite(ConsoleColor.Magenta, "Got Item: " + i.ItemId + " " + i.ItemCount + "x");
                          alreadygot.Add(i.ItemId);
                      }
                  }
                  alreadygot.Clear();
              }
  
              Console.Title = profile.PlayerData.Username + " lvl" + stats.Level + "-(" + (stats.Experience - stats.PrevLevelXp -
                  StringUtils.getExpDiff(stats.Level)).ToString("N0") + "/" + (stats.NextLevelXp - stats.PrevLevelXp - StringUtils.getExpDiff(stats.Level)).ToString("N0") + "|" + Math.Round(curexppercent, 2) + "%)| Stardust: " + profile.PlayerData.Currencies.ToArray()[1].Amount + "| " + _botStats.ToString();
              if (_clientSettings.CheckWhileRunning)
              {
                  if (getNewestVersion() > Assembly.GetEntryAssembly().GetName().Version)
                  {
                      if (_clientSettings.autoUpdate)
                      {
                          Form update = new Update();
                          update.ShowDialog();
                      }
                      else
                      {
                          DialogResult dialogResult = MessageBox.Show("There is an Update on Github. do you want to open it ?", "Newest Version: " + getNewestVersion(), MessageBoxButtons.YesNo);
                          if (dialogResult == DialogResult.Yes)
                          {
                              Process.Start("https://github.com/Ar1i/PokemonGo-Bot");
                          }
                          else if (dialogResult == DialogResult.No)
                          {
                              //nothing   
                          }
                      }
                  }
              }
          }
  
          private async Task LogStatsEtc()
          {
              count = 0;
              if (_clientSettings.UseLuckyEggIfNotRunning || _clientSettings.UseLuckyEggGUIClick)
              {
                  _clientSettings.UseLuckyEggGUIClick = false;
                  await _client.Inventory.UseLuckyEgg(_client);
              }
  
              if (_clientSettings.EvolvePokemonsIfEnoughCandy)
              {
                  await EvolveAllPokemonWithEnoughCandy();
              }
  
              if (_clientSettings.AutoIncubate)
              {
                  await StartIncubation();
              }
  
              await TransferDuplicatePokemon(_clientSettings.keepPokemonsThatCanEvolve, _clientSettings.TransferFirstLowIV);
              //await RecycleItems();               
              await StatsLog(_client);
              await SetCheckTimeToRun();
          }
  
          private async Task SetCheckTimeToRun()
          {
              #region Time to Run
              if (_clientSettings.TimeToRun != 0)
              {
                  if (timetorunstamp == -10000)
                  {
                      timetorunstamp = (_clientSettings.TimeToRun * 60 * 1000) + ((long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds);
                  }
                  else
                  {
                      var runTimeRemaining = timetorunstamp - (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
                      if (runTimeRemaining <= 0)
                      {
                          Logger.ColoredConsoleWrite(ConsoleColor.Red, "Time To Run Reached or Exceeded...Walking back to default location and stopping bot");
                          if (_clientSettings.UseGoogleMapsAPI)
                          {
                              await WalkWithRouting(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchandFarm);
                          }
                          else
                          {
                              var walkHome = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
                          }
                          StringUtils.CheckKillSwitch(true);
                      }
                      else
                      {
                          Logger.ColoredConsoleWrite(ConsoleColor.Blue, String.Format("Remaining Time to Run: {0} minutes", Math.Round(runTimeRemaining / 1000 / 60, 2)));
                      }
                  }
              }
              #endregion
  
              #region Breaks
              if (_clientSettings.UseBreakFields)
              {
                  if (pausetimestamp > -10000)
                  {
                      var walkTimeRemaining = pausetimestamp - (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
                      if (walkTimeRemaining <= 0)
                      {
                          pausetimestamp = -10000;
                          _clientSettings.pauseAtPokeStop = true;
                          resumetimestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds + _clientSettings.BreakLength * 60 * 1000;
                          Logger.ColoredConsoleWrite(ConsoleColor.Blue, String.Format("Break Time! Pause walking for {0} minutes", _clientSettings.BreakLength));
                      }
                      else
                      {
                          Logger.ColoredConsoleWrite(ConsoleColor.Blue, String.Format("Remaining Time until break: {0} minutes", Math.Round(walkTimeRemaining / 1000 / 60, 2)));
                      }
                  }
                  else if (resumetimestamp == -10000)
                  {
                      pausetimestamp = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds + _clientSettings.BreakInterval * 60 * 1000;
                      Logger.ColoredConsoleWrite(ConsoleColor.Blue, String.Format("Remaining Time until break: {0} minutes", _clientSettings.BreakInterval));
                  }
                  if (resumetimestamp > -10000)
                  {
                      var breakTimeRemaining = resumetimestamp - (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds;
                      if (breakTimeRemaining <= 0)
                      {
                          resumetimestamp = -10000;
                          _clientSettings.pauseAtPokeStop = false;
                          Logger.ColoredConsoleWrite(ConsoleColor.Green, "Break over, back to walking!");
                      }
                      else
                      {
                          Logger.ColoredConsoleWrite(ConsoleColor.Blue, String.Format("Remaining Time until resume walking: {0} minutes", Math.Round(breakTimeRemaining / 1000 / 60, 2)));
                      }
                  }
              }
              #endregion
  
              #region Log Catch Disabled
              //add logging for pokemon catch disabled here for now to prevent spamming
              if (!_clientSettings.CatchPokemon)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Red, $"Catching Pokemon Disabled in Client Settings - Skipping all pokemon");
              }
              #endregion
  
              #region Check Run Count Limits
  
              #region Catch Pokemon Count Check
              if (pokemonCatchCount >= _clientSettings.PokemonCatchLimit)
              {
  
                  if (_clientSettings.FarmPokestops)
                  {
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokemon Catch Limit Reached - Bot will only farm pokestops");
                      _clientSettings.CatchPokemon = false;
                  }
                  else
                  {
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokemon Catch Limit Reached and not farming pokestops - Bot will return to default location and stop");
                      if (_clientSettings.UseGoogleMapsAPI)
                      {
                          await WalkWithRouting(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchandFarm);
                      }
                      else
                      {
                          var walkHome = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
                      }
                      StringUtils.CheckKillSwitch(true);
                  }
              }
              #endregion
  
              #region Farm Pokestops Check
              if (pokeStopFarmedCount >= _clientSettings.PokestopFarmLimit)
              {
                  if (_clientSettings.CatchPokemon)
                  {
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokestop Farmed Limit Reached - Bot will only catch pokemon");
                      _clientSettings.FarmPokestops = false;
                  }
                  else
                  {
                      Logger.ColoredConsoleWrite(ConsoleColor.Green, "Pokestop Farmed Limit Reached and not catching pokemon - Bot will return to default location and stop");
                      if (_clientSettings.UseGoogleMapsAPI)
                      {
                          await WalkWithRouting(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchandFarm);
                      }
                      else
                      {
                          var walkHome = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
                      }
                      StringUtils.CheckKillSwitch(true);
                  }
              }
              #endregion
  
              #region XP Check
              if (startingXP != -10000 && currentxp != -10000 && (currentxp = -startingXP) >= _clientSettings.XPFarmedLimit)
              {
                  Logger.ColoredConsoleWrite(ConsoleColor.Green, "XP Farmed Limit Reached - Bot will return to default location and stop");
                  if (_clientSettings.UseGoogleMapsAPI)
                  {
                      await WalkWithRouting(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude, _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchandFarm);
                  }
                  else
                  {
                      var walkHome = await _navigation.HumanLikeWalking(new GeoCoordinate(_clientSettings.DefaultLatitude, _clientSettings.DefaultLongitude), _clientSettings.WalkingSpeedInKilometerPerHour, ExecuteCatchAllNearbyPokemons);
                  }
                  StringUtils.CheckKillSwitch(true);
              }
              #endregion
  
              #endregion
          }
  
          #endregion
  
          #region Catch, Farm and Walk Logic
          private async Task Espiral(Client client, FortData[] pokeStops)
          {
              //Intento de pajarera 1...
              await ExecuteCatchAllNearbyPokemons();
              Logger.ColoredConsoleWrite(ConsoleColor.Blue, "Starting Archimedean spiral");
              int i2 = 0;
              double angle;
              double centerx;
              double centery;
              double xx;
              double yy;
              Boolean salir = true;
              double distancia;
              double cantidadvar = 0.0001;
              double recorrido = _client.Settings.MaxWalkingRadiusInMeters;
  
              pokeStops = pokeStops.Where(i => LocationUtils.CalculateDistanceInMeters(_client.CurrentLatitude, _client.CurrentLongitude, i.Latitude, i.Longitude) <= _clientSettings.MaxWalkingRadiusInMeters).ToArray();
  
              centerx = _client.CurrentLatitude;
              centery = _client.CurrentLongitude;
  
              if (recorrido <= 100) cantidadvar = 0.00008;
              if (recorrido > 100 && recorrido <= 500) cantidadvar = 0.00009;
              if (recorrido > 500 && recorrido <= 1000) cantidadvar = 0.0001;
  
gt:             if (recorrido > 1000) cantidadvar = 0.0002;