using RestSharp;
using System.Text;
using System.Threading.Tasks;
using System;
using Adrenak.Unex;
using UnityEngine;
namespace Adrenak.UniMap {
///
/// Used to get the address of a set of coordinates
///
public class GeolookupRequest {
const string k_BaseURL = "https://maps.googleapis.com/maps/api/geocode/json?";
///
/// The Google Maps API key being used
///
public string Key { get; private set; }
///
/// The Location being looked up currently
///
public Location Location { get; private set; }
///
/// Creats an instance for lookup requests
///
///
public GeolookupRequest(string key) {
Key = key;
}
///
/// Gets the URL for the given parameters
///
///
public string GetURL() {
if (Key.IsNullOrEmpty())
throw new Exception("No key provided");
var builder = new StringBuilder(k_BaseURL);
builder.Append("key=").Append(Key);
builder.Append("&latlng=").Append(Location.lat).Append(",").Append(Location.lng);
return builder.ToString();
}
///
/// Sends the request for a set of coordinates
///
/// The latitude of the coordinates to be looked up
/// The longitude of the coordinates to be looked up
/// Callback for a successful response
/// Callback for an unsuccessful response
public void Send(Location location, Action onSuccess, Action onFailure) {
Location = location;
var client = new RestClient();
var request = new RestRequest(GetURL(), Method.GET);
client.ExecuteAsync(request, response => {
Dispatcher.Enqueue(() => {
if (response.IsSuccessful()) {
var model = JsonUtility.FromJson(response.Content);
if (model != null)
onSuccess?.Invoke(model);
else {
var exception = new Exception("Could not deserialize", response.GetException());
onFailure?.Invoke(exception);
}
}
else {
var exception = new Exception("Unsuccessful response for Geolookup", response.GetException());
onFailure?.Invoke(exception);
}
});
});
}
///
/// Sends the request for a set of coordinates and returns a task for the response
///
/// The latitude of the coordinates to be looked up
/// The longitude of the coordinates to be looked up
///
public Task Send(Location location) {
var source = new TaskCompletionSource();
Send(
location,
response => source.SetResult(response),
exception => source.SetException(exception)
);
return source.Task;
}
}
}