Assignment for Location Calculation
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.

80 lines
2.8 KiB

  1. using Microsoft.AspNetCore.Http;
  2. using POCDistance.DAL;
  3. using POCDistance.Models;
  4. using POCDistance.Util;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. namespace POCDistance.Service
  8. {
  9. public class LocationService : ILocationService
  10. {
  11. private readonly IHttpContextAccessor _httpContextAccessor;
  12. private readonly IDataSourceAdapter _dataAdapter;
  13. public LocationService(IHttpContextAccessor httpContextAccessor, IDataSourceAdapter dataAdapter)
  14. {
  15. _httpContextAccessor = httpContextAccessor;
  16. _dataAdapter = dataAdapter;
  17. }
  18. public List<LocationModel> GetAll()
  19. {
  20. var locations = new List<LocationModel>();
  21. if (!string.IsNullOrEmpty(_httpContextAccessor.HttpContext.Session.GetString("LocationData")))
  22. {
  23. locations = _httpContextAccessor.HttpContext.Session.GetObjectFromJson<List<LocationModel>>("LocationData");
  24. }
  25. else
  26. {
  27. locations = _dataAdapter.GetLocations();
  28. _httpContextAccessor.HttpContext.Session.SetObjectAsJson("LocationData", locations);
  29. }
  30. return locations;
  31. }
  32. public List<LocationModel> GetManyByZipCode(string zipCode)
  33. {
  34. if (!string.IsNullOrWhiteSpace(zipCode) && zipCode.Length > 1)
  35. {
  36. var locations = GetAll();
  37. var query = locations.Where(l => l.ZipCode.StartsWith(zipCode));
  38. return query.ToList();
  39. }
  40. return new List<LocationModel>();
  41. }
  42. public LocationModel GetByZipCode(string zipCode)
  43. {
  44. var _location = GetManyByZipCode(zipCode);
  45. return _location.OrderByDescending(l => l.Country).FirstOrDefault();
  46. }
  47. public DistanceModel GetDistanceByZipCode(string zipCode1, string zipCode2)
  48. {
  49. double distance = 0.0;
  50. double loc_lat1, loc_long1, loc_lat2, loc_long2;
  51. var model = new DistanceModel();
  52. var location1 = GetByZipCode(zipCode1);
  53. var location2 = GetByZipCode(zipCode2);
  54. if (location1 != null
  55. && location2 != null
  56. && double.TryParse(location1.Latitude, out loc_lat1)
  57. && double.TryParse(location1.Longitude, out loc_long1)
  58. && double.TryParse(location2.Latitude, out loc_lat2)
  59. && double.TryParse(location2.Longitude, out loc_long2))
  60. {
  61. distance = CalculateDistance.GetDistance(loc_lat1, loc_long1, loc_lat2, loc_long2);
  62. model.Distance = distance.ToString("0.00");
  63. model.FromCity = location1.City;
  64. model.ToCity = location2.City;
  65. model.Unit = "km";
  66. }
  67. return model;
  68. }
  69. }
  70. }