using BeWo.Data.Access; using BeWo.Data.Entities; using System; using System.Collections.Generic; using System.Linq; namespace BeWo.Service.ServiceUtils.DistanceCalculator { public static class AddressRouteManager { public static IDistanceAPI DistanceAPI { get; set; } static AddressRouteManager() { DistanceAPI = //new GoogleDistanceMatrixApi(); new OpenrouteServiceAPI(); } public static AddressRouteMatrix GetMatrix(Address[] origins, Address[] destinations) { var routes = DAOFactory.GenericDAO.GetAll(); var matrix = new AddressRouteMatrix(origins, destinations); LoadExistingData(ref matrix, routes, out var needUpdate); var requests = needUpdate.Union(matrix.GetUnkownRoutes()).ToList(); // Alles aktuell if (!requests.Any()) return matrix; var ori2req = requests.Select(x => x.Origin).ToHashSet(); var des2req = requests.Select(x => x.Destination).ToHashSet(); DistanceAPI.RequestMissingData(ref matrix, ori2req, des2req); foreach (var req in requests) { var route = matrix.GetRoute(req.Origin, req.Destination); if (route is null) throw new NotImplementedException("Unerwartetes Verhalten #4314513094871"); route.Origin_Version = route.Origin.Version.Value; route.Destination_Version = route.Destination.Version.Value; if (!route.Version.HasValue) { // Neu DAOFactory.GenericDAO.Insert(req); } else { // Update DAOFactory.GenericDAO.Update(req); } } return matrix; } public static void LoadExistingData(ref AddressRouteMatrix matrix, IList routes, out List needUpdate) { needUpdate = new List(); foreach (var route in routes) { var origin = route.Origin; var destination = route.Destination; if (!matrix.CanUseRoute(origin, destination)) continue; if (origin.Version == route.Origin_Version && destination.Version == route.Destination_Version) { // Ist aktuell matrix.SetRoute(origin, destination, route); } else { // Braucht Update matrix.SetRoute(origin, destination, route); needUpdate.Add(route); } } } public static string AddressToString(Address address) { return $"{address.Street}, {address.PostalCode}, {address.Town}, {address.State}, {address.Country}"; } } }