You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

484 lines
18 KiB

1 year ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. //using Android.Content.PM;
  8. using GMCabsDriverAssistant;
  9. using GMCabsDriverAssistant.Messages;
  10. using GMCabsDriverAssistant.Models;
  11. using GMCabsDriverAssistant.Services;
  12. using GMCabsDriverAssistant.Utils;
  13. using GMCabsDriverAssistantSolution.Models.Rydo;
  14. using GMCabsDriverAssistantSolution.Views;
  15. using Microsoft.Maui;
  16. using Microsoft.Maui.Controls;
  17. using Sentry;
  18. namespace GMCabsDriverAssistantSolution.ViewModels
  19. {
  20. public class HomeViewModel : BaseViewModel
  21. {
  22. #region Constants
  23. private const int LOCATION_CHECK_TIME_INTERVAL = 10;
  24. private const int LOCATION_READ_TIMEOUT = 10;
  25. private const double LOCATION_DISTANCE = 0.01;
  26. private double lastLatitude = 0.00, lastLongitude = 0.00;
  27. #endregion Constants
  28. #region Fields
  29. public int seconds = 180;
  30. public string timerSeconds = "3:00";
  31. public string pickUpAddress = "";
  32. public string dropUpAddress = "";
  33. private bool isVisibleAcceptBookingView = false;
  34. private readonly LoginResponseDto loginResponseDto = new LoginResponseDto();
  35. private bool hasUnreadNotifications;
  36. private bool isBookingAvailable;
  37. private CancellationTokenSource cts;
  38. private List<Guid> receivedBookingIDs;
  39. public List<Guid> availableBookingIDs = new List<Guid>();
  40. public bool isLocationPermitted;
  41. #endregion
  42. #region Properties
  43. public bool IsVisibleAcceptBookingView
  44. {
  45. get => isVisibleAcceptBookingView;
  46. set
  47. {
  48. SetProperty(ref isVisibleAcceptBookingView, value);
  49. CustomTimer();
  50. }
  51. }
  52. public string PickUpAddress
  53. {
  54. get => pickUpAddress;
  55. set
  56. {
  57. SetProperty(ref pickUpAddress, value);
  58. }
  59. }
  60. public string DropUpAddress
  61. {
  62. get => dropUpAddress;
  63. set
  64. {
  65. SetProperty(ref dropUpAddress, value);
  66. }
  67. }
  68. public bool HasUnreadNotifications
  69. {
  70. get => hasUnreadNotifications;
  71. set => SetProperty(ref hasUnreadNotifications, value);
  72. }
  73. public bool IsBookingAvailable
  74. {
  75. get => isBookingAvailable;
  76. set => SetProperty(ref isBookingAvailable, value);
  77. }
  78. public string TimerSeconds
  79. {
  80. get => timerSeconds;
  81. set => SetProperty(ref timerSeconds, value);
  82. }
  83. public Location CurrentLocation { get; set; }
  84. readonly ILocationConsent locationConsent;
  85. #endregion
  86. #region Constructor
  87. public HomeViewModel()
  88. {
  89. Title = "Home";
  90. GetToken();
  91. locationConsent = DependencyService.Get<ILocationConsent>();
  92. //HandleReceivedMessages();
  93. //locationConsent.GetLocationConsent();
  94. }
  95. #endregion
  96. #region Methods
  97. [Obsolete]
  98. public async Task OnAppearing()
  99. {
  100. isLocationPermitted = Preferences.Get(SecureStorageData.IsLocationPermitted, false);
  101. //SendForegroundAlarmManager();
  102. if (Device.RuntimePlatform != Device.iOS)
  103. {
  104. if (isLocationPermitted)
  105. {
  106. if (!DependencyService.Resolve<IForegroundService>().IsForeGroundServiceRunning())
  107. {
  108. Preferences.Set("isForeground", "YES");
  109. DependencyService.Resolve<IForegroundService>().StartMyForegroundService();
  110. }
  111. }
  112. }
  113. else
  114. {
  115. var message = new StartServiceMessage();
  116. MessagingCenter.Send(message, "ServiceStarted");
  117. }
  118. UpdateDriverAppSelectedPermissions();
  119. GetUnreadNotificationCount();
  120. await GetCurrentLocation();
  121. await GetBookingAvailable();
  122. CheckBookingAndNotificationAvailibility();
  123. }
  124. public async void GetToken()
  125. {
  126. var token = Preferences.Get(SecureStorageData.Token, "");
  127. loginResponseDto.Token = Guid.Parse(token);
  128. }
  129. [Obsolete]
  130. public async void GetUnreadNotificationCount()
  131. {
  132. var token = Preferences.Get(SecureStorageData.Token, "");
  133. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  134. var unreadNotification = await gmCabsDriverService.GetUnreadNotificationCount(token);
  135. if (unreadNotification != null)
  136. {
  137. if (unreadNotification.StatusCode == Constant.UNAUTHORIZED_CODE)
  138. {
  139. GoToLoginPage();
  140. }
  141. else
  142. {
  143. if (unreadNotification.UnreadNotificationCount > 0)
  144. {
  145. HasUnreadNotifications = true;
  146. }
  147. else
  148. {
  149. HasUnreadNotifications = false;
  150. }
  151. }
  152. }
  153. }
  154. [Obsolete]
  155. private void GoToLoginPage()
  156. {
  157. Device.BeginInvokeOnMainThread(async () =>
  158. {
  159. if (Device.RuntimePlatform != Device.iOS)
  160. {
  161. Preferences.Set("isForeground", "NO");
  162. DependencyService.Resolve<IForegroundService>().StopMyForegroundService();
  163. }
  164. else if (Device.RuntimePlatform == Device.iOS)
  165. {
  166. var message = new StopServiceMessage();
  167. MessagingCenter.Send(message, "ServiceStopped");
  168. }
  169. var token = Preferences.Get(SecureStorageData.Token, "");
  170. Debug.WriteLine("TOKEN-------------", token);
  171. var lastLatitude = Convert.ToDouble(Preferences.Get("lastLat", "0"));
  172. var lastLongitude = Convert.ToDouble(Preferences.Get("lastLng", "0"));
  173. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  174. await gmCabsDriverService.LogoutDriverApp(token, lastLatitude, lastLongitude);
  175. SecureStorage.RemoveAll();
  176. Preferences.Clear();
  177. SentrySdk.ConfigureScope(scope =>
  178. {
  179. scope.User = null;
  180. });
  181. await Shell.Current.GoToAsync($"//{nameof(LoginPage)}");
  182. });
  183. }
  184. private async Task GetBookingAvailable()
  185. {
  186. var canAcceptBookings = Preferences.Get(SecureStorageData.CanAcceptBookings, false);
  187. if (!canAcceptBookings || CurrentLocation == null)
  188. {
  189. return;
  190. }
  191. var accessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
  192. var driverId = Preferences.Get(LoginResponseDto.USER_CODE, "");
  193. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  194. availableBookingIDs = await gmCabsDriverService.GetBookingAvailableCount(accessToken, driverId, CurrentLocation.Latitude, CurrentLocation.Longitude);
  195. var cachedeBookingIds = await App.Database.GetBookingIdsAsync();
  196. if (availableBookingIDs != null && availableBookingIDs.Count > 0)
  197. {
  198. bool areNewBookings = false;
  199. //IEnumerable<Guid> newBookings = null;
  200. List<Guid> cachedBookings = new List<Guid>();
  201. if (cachedeBookingIds.Count == 0)
  202. {
  203. await App.Database.SaveBookingIdsAsync(availableBookingIDs.Select(g => g.ToString()));
  204. areNewBookings = true;
  205. }
  206. else
  207. {
  208. foreach (var availableBooking in cachedeBookingIds)
  209. {
  210. cachedBookings.Add(Guid.Parse(availableBooking.BookingID));
  211. }
  212. int cachedBookingsCount = cachedBookings.Count();
  213. var newBookings = availableBookingIDs.Except(cachedBookings);
  214. if (newBookings.Count() > 0)
  215. {
  216. Console.WriteLine($"New Bookings Count: {newBookings.Count()}");
  217. await App.Database.SaveBookingIdsAsync(newBookings.Select(g => g.ToString()));
  218. areNewBookings = true;
  219. }
  220. }
  221. IsBookingAvailable = true;
  222. //if (Device.RuntimePlatform == Device.iOS)
  223. //{
  224. // if (areNewBookings)
  225. // {
  226. // var player = CrossSimpleAudioPlayer.Current;
  227. // player.Load("newbooking.wav");
  228. // player.Play();
  229. // }
  230. //}
  231. }
  232. else
  233. {
  234. IsBookingAvailable = false;
  235. if (cachedeBookingIds.Count != 0)
  236. {
  237. foreach (var availableBooking in cachedeBookingIds)
  238. {
  239. await App.Database.DeleteBookingIdsAsync(availableBooking);
  240. }
  241. }
  242. }
  243. }
  244. async Task GetCurrentLocation()
  245. {
  246. try
  247. {
  248. if (isLocationPermitted)
  249. {
  250. CurrentLocation = await Geolocation.GetLastKnownLocationAsync();
  251. if (CurrentLocation == null)
  252. {
  253. var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(LOCATION_READ_TIMEOUT));
  254. cts = new CancellationTokenSource();
  255. // CurrentLocation = await Geolocation.GetLocationAsync(request, cts.Token);
  256. CurrentLocation = await Geolocation.GetLocationAsync(new GeolocationRequest
  257. {
  258. Timeout = TimeSpan.FromSeconds(50),
  259. DesiredAccuracy = GeolocationAccuracy.Medium
  260. });
  261. }
  262. }
  263. }
  264. catch (FeatureNotSupportedException fnsEx)
  265. {
  266. // Handle not supported on device exception
  267. }
  268. catch (FeatureNotEnabledException fneEx)
  269. {
  270. // Handle not enabled on device exception
  271. }
  272. catch (PermissionException pEx)
  273. {
  274. // Handle permission exception
  275. }
  276. catch (Exception ex)
  277. {
  278. // Unable to get location
  279. }
  280. }
  281. public void OnDisappearing()
  282. {
  283. if (cts != null && !cts.IsCancellationRequested)
  284. cts.Cancel();
  285. }
  286. [Obsolete]
  287. private void CustomTimer()
  288. {
  289. Device.StartTimer(TimeSpan.FromSeconds(1), () =>
  290. {
  291. if (!isVisibleAcceptBookingView)
  292. {
  293. return false;
  294. }
  295. if (seconds > 0)
  296. {
  297. --seconds;
  298. TimerSeconds = seconds / 60 + ":" + (seconds % 60 <= 9 ? "0" + seconds % 60 : "" + seconds % 60);
  299. return true;
  300. }
  301. else
  302. {
  303. IsVisibleAcceptBookingView = false;
  304. return false;
  305. }
  306. });
  307. }
  308. void HandleReceivedMessages()
  309. {
  310. //MessagingCenter.Subscribe<LocationMessage>(this, "Location", message =>
  311. //{
  312. // Device.BeginInvokeOnMainThread(async () =>
  313. // {
  314. // Console.WriteLine(message.Latitude);
  315. // Console.WriteLine(message.Longitude);
  316. // var token = Preferences.Get(SecureStorageData.Token,"");
  317. // if (token != null)
  318. // {
  319. // GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  320. // LocationUpdateRequestDto locationUpdateRequestDto = new LocationUpdateRequestDto();
  321. // if (lastLatitude == 0.00 && lastLongitude == 0.00)
  322. // {
  323. // lastLatitude = message.Latitude;
  324. // lastLongitude = message.Longitude;
  325. // locationUpdateRequestDto.Latitude = message.Latitude;
  326. // locationUpdateRequestDto.Longitude = message.Longitude;
  327. // await gmCabsDriverService.SendDriverLocation(token, locationUpdateRequestDto);
  328. // }
  329. // else
  330. // {
  331. // Location lastLocation = new Location(lastLatitude, lastLongitude);
  332. // Location currentLocation = new Location(message.Latitude, message.Longitude);
  333. // double kilometers = Location.CalculateDistance(lastLocation, currentLocation, DistanceUnits.Kilometers);
  334. // if (kilometers > LOCATION_DISTANCE)
  335. // {
  336. // lastLatitude = message.Latitude;
  337. // lastLongitude = message.Longitude;
  338. // locationUpdateRequestDto.Latitude = message.Latitude;
  339. // locationUpdateRequestDto.Longitude = message.Longitude;
  340. // await gmCabsDriverService.SendDriverLocation(token, locationUpdateRequestDto);
  341. // }
  342. // }
  343. // Preferences.Set("lastLat", message.Latitude);
  344. // Preferences.Set("lastLng", message.Longitude);
  345. // }
  346. // });
  347. //});
  348. MessagingCenter.Subscribe<StopServiceMessage>(this, "ServiceStopped", message =>
  349. {
  350. Device.BeginInvokeOnMainThread(() =>
  351. {
  352. // UserMessage = "Location Service has been stopped!";
  353. Console.WriteLine("Location Service has been stopped!");
  354. });
  355. });
  356. MessagingCenter.Subscribe<LocationErrorMessage>(this, "LocationError", message =>
  357. {
  358. Device.BeginInvokeOnMainThread(() =>
  359. {
  360. // UserMessage = "There was an error updating location!";
  361. Console.WriteLine("There was an error updating location!");
  362. });
  363. });
  364. }
  365. private async Task GetBookingsWithOutNotificationSound()
  366. {
  367. var accessToken = Preferences.Get(EftposLoginResponse.RYDO_ACCESS_TOKEN, "");
  368. var driverId = Preferences.Get(LoginResponseDto.USER_CODE, "");
  369. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  370. availableBookingIDs = await gmCabsDriverService.GetBookingAvailableCount(accessToken, driverId, CurrentLocation.Latitude, CurrentLocation.Longitude);
  371. if (availableBookingIDs.Count == 0)
  372. {
  373. IsBookingAvailable = false;
  374. }
  375. }
  376. [Obsolete]
  377. private void CheckBookingAndNotificationAvailibility()
  378. {
  379. Device.StartTimer(TimeSpan.FromSeconds(LOCATION_CHECK_TIME_INTERVAL), () =>
  380. {
  381. var isForeground = ShareConstant.IsInForeground;
  382. Task.Run(async () =>
  383. {
  384. //GetUnreadNotificationCount(); //For avoiding duplicate call of UnreadCount API
  385. await GetBookingsWithOutNotificationSound();
  386. });
  387. return isForeground;
  388. });
  389. }
  390. [Obsolete]
  391. private void SendForegroundAlarmManager()
  392. {
  393. Device.StartTimer(TimeSpan.FromMinutes(Constant.TIMER_MINUTES), () =>
  394. {
  395. var serviceRunningStatus = DependencyService.Resolve<IForegroundService>().IsForeGroundServiceRunning();
  396. if (serviceRunningStatus)
  397. {
  398. DependencyService.Resolve<IAlarmService>().StartMyAlarmService();
  399. }
  400. return serviceRunningStatus;
  401. });
  402. }
  403. [Obsolete]
  404. public async Task UpdateLocation()
  405. {
  406. await GetCurrentLocation();
  407. if (CurrentLocation != null)
  408. {
  409. var response = await UpdateLocationOnServer(CurrentLocation.Latitude, CurrentLocation.Longitude);
  410. if (response == Constant.SUCCESS_CODE)
  411. {
  412. await GetBookingAvailable();
  413. }
  414. else if (response == Constant.UNAUTHORIZED_CODE)
  415. {
  416. GoToLoginPage();
  417. }
  418. }
  419. }
  420. private async Task<int> UpdateLocationOnServer(double currentLatitude, double currentLongitude)
  421. {
  422. var token = Preferences.Get(SecureStorageData.Token, "");
  423. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  424. LocationUpdateRequestDto locationUpdateRequestDto = new LocationUpdateRequestDto();
  425. locationUpdateRequestDto.Latitude = currentLatitude;
  426. locationUpdateRequestDto.Longitude = currentLongitude;
  427. var responce = await gmCabsDriverService.SendDriverLocation(token, locationUpdateRequestDto);
  428. Preferences.Set("lastLat", currentLatitude);
  429. Preferences.Set("lastLng", currentLongitude);
  430. return responce;
  431. }
  432. private async void UpdateDriverAppSelectedPermissions()
  433. {
  434. var token = Preferences.Get(SecureStorageData.Token, "");
  435. var isLocationPermitted = Preferences.Get(SecureStorageData.IsLocationPermitted, false);
  436. var isBatteryOptimizationDisabled = Preferences.Get(SecureStorageData.IsBatteryOptimizationDisabled, false);
  437. var driverAppSelectedPermissionsDto = new DriverAppSelectedPermissionsDto();
  438. GMCabsDriverService gmCabsDriverService = new GMCabsDriverService();
  439. driverAppSelectedPermissionsDto.LocationSetToAlways = isLocationPermitted;
  440. driverAppSelectedPermissionsDto.BatteryOptimisationDisabled = isBatteryOptimizationDisabled;
  441. await gmCabsDriverService.DriverAppSelectedPermissions(token, driverAppSelectedPermissionsDto);
  442. }
  443. #endregion
  444. }
  445. }