using Microsoft.Maui.Storage; using System.Globalization; using System.Text.Json; namespace MauiWeather; public partial class MainPage : ContentPage { private static readonly HttpClient Client = new() { Timeout = TimeSpan.FromSeconds(15) }; private readonly (string Name, double Lat, double Lon)[] cities = [ ("Kuala Lumpur", 3.1390, 101.6869), ("Singapore", 1.3521, 103.8198), ("Tokyo", 35.6762, 139.6503), ("London", 51.5072, -0.1276) ]; public MainPage() { InitializeComponent(); CityPicker.ItemsSource = cities.Select(c => c.Name).ToList(); int saved = Preferences.Default.Get("cityIndex", 0); CityPicker.SelectedIndex = Math.Clamp(saved, 0, cities.Length - 1); } private async void OnRefreshClicked(object sender, EventArgs e) { int index = CityPicker.SelectedIndex; if (index < 0) return; Preferences.Default.Set("cityIndex", index); var city = cities[index]; string lat = city.Lat.ToString(CultureInfo.InvariantCulture); string lon = city.Lon.ToString(CultureInfo.InvariantCulture); string url = "https://api.open-meteo.com/v1/forecast" + $"?latitude={lat}&longitude={lon}" + "¤t=temperature_2m,relative_humidity_2m,wind_speed_10m"; RefreshButton.IsEnabled = false; StatusLabel.Text = $"Loading {city.Name}..."; try { using var response = await Client.GetAsync(url); response.EnsureSuccessStatusCode(); string jsonText = await response.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(jsonText); var current = doc.RootElement.GetProperty("current"); double temp = current.GetProperty("temperature_2m").GetDouble(); double humidity = current.GetProperty("relative_humidity_2m").GetDouble(); double wind = current.GetProperty("wind_speed_10m").GetDouble(); TemperatureLabel.Text = $"{temp:0.#} °C"; HumidityLabel.Text = $"{humidity:0}%"; WindLabel.Text = $"{wind:0.#} km/h"; StatusLabel.Text = $"Current conditions for {city.Name}."; } catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException or KeyNotFoundException) { StatusLabel.Text = "Weather unavailable. Check the connection and try again."; } finally { RefreshButton.IsEnabled = true; } } }