using System.Text.Json;
namespace LocationTrackerApp.Services;
///
/// Provides configuration services for the application
///
public class ConfigurationService : IConfigurationService
{
private readonly string _googleMapsApiKey;
///
/// Initializes a new instance of the ConfigurationService
///
public ConfigurationService()
{
_googleMapsApiKey = LoadGoogleMapsApiKey();
}
///
/// Gets the Google Maps API key
///
public string GetGoogleMapsApiKey()
{
return _googleMapsApiKey;
}
///
/// Loads the Google Maps API key from configuration
///
private string LoadGoogleMapsApiKey()
{
try
{
// First, try to get from environment variable
var envApiKey = Environment.GetEnvironmentVariable("GoogleMapsApiKey");
if (!string.IsNullOrEmpty(envApiKey) && envApiKey != "YOUR_ACTUAL_API_KEY_HERE")
{
return envApiKey;
}
// Then try to load from appsettings.json
var configPath = Path.Combine(FileSystem.AppDataDirectory, "appsettings.json");
if (File.Exists(configPath))
{
var json = File.ReadAllText(configPath);
var config = JsonSerializer.Deserialize(json);
if (config.TryGetProperty("GoogleMaps", out var googleMaps) &&
googleMaps.TryGetProperty("ApiKey", out var apiKeyElement))
{
var apiKey = apiKeyElement.GetString();
if (!string.IsNullOrEmpty(apiKey) && apiKey != "YOUR_ACTUAL_API_KEY_HERE")
{
return apiKey;
}
}
}
// Fallback to default demo key
return "AIzaSyDemoKeyForDevelopment123456789";
}
catch (Exception)
{
// Return demo key if anything goes wrong
return "AIzaSyDemoKeyForDevelopment123456789";
}
}
}