-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.axaml.cs
More file actions
288 lines (248 loc) · 11.6 KB
/
MainWindow.axaml.cs
File metadata and controls
288 lines (248 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Avalonia.Threading; // Added for DispatcherTimer
using System.Net.Http;
using System.Net.Http.Json;
using System;
using System.Text.Json.Serialization;
using System.Collections.Generic;
using System.Globalization;
using System.Threading.Tasks;
using System.IO;
using System.Linq;
namespace Weather_GUI;
public partial class MainWindow : Window
{
private static readonly HttpClient http = new HttpClient() { Timeout = TimeSpan.FromSeconds(10) };
private readonly string _historyFile = "search_history.txt";
private List<string> _recentCities = new();
private DispatcherTimer? _refreshTimer;
private string _currentCity = "";
public MainWindow()
{
InitializeComponent();
http.DefaultRequestHeaders.Clear();
http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (WeatherProject)");
CitySearch.KeyDown += OnSearchKeyDown;
// 1. Load history
LoadHistory();
// 2. Initialize the 2-minute auto-refresh timer
SetupAutoRefresh();
}
private void SetupAutoRefresh()
{
_refreshTimer = new DispatcherTimer
{
Interval = TimeSpan.FromMinutes(2)
};
_refreshTimer.Tick += async (s, e) => {
if (!string.IsNullOrEmpty(_currentCity))
{
// Auto-refresh the current city without showing "Fetching..."
await PerformSearch(_currentCity, isAutoRefresh: true);
}
};
_refreshTimer.Start();
}
private void LoadHistory()
{
try {
if (File.Exists(_historyFile)) {
_recentCities = File.ReadAllLines(_historyFile).ToList();
UpdateHistoryUI();
// Optional: Automatically load the last searched city on startup
if (_recentCities.Count > 0)
{
_currentCity = _recentCities[0];
_ = PerformSearch(_currentCity);
}
}
} catch { }
}
private void SaveCityToHistory(string city)
{
city = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(city.ToLower().Trim());
_recentCities.Remove(city);
_recentCities.Insert(0, city);
_recentCities = _recentCities.Take(5).ToList();
try {
File.WriteAllLines(_historyFile, _recentCities);
UpdateHistoryUI();
} catch { }
}
private void UpdateHistoryUI()
{
HistoryPanel.Children.Clear();
foreach (var city in _recentCities)
{
var btn = new Button {
Content = city,
Padding = new Avalonia.Thickness(12, 4),
CornerRadius = new Avalonia.CornerRadius(15),
Background = Brushes.Transparent,
BorderBrush = Brushes.LightGray,
BorderThickness = new Avalonia.Thickness(1),
Foreground = Brushes.White,
FontSize = 11,
Margin = new Avalonia.Thickness(0, 0, 5, 0)
};
btn.Click += async (s, e) => {
CitySearch.Text = city;
await PerformSearch(city);
};
HistoryPanel.Children.Add(btn);
}
if (_recentCities.Count > 0)
{
var clearBtn = new Button {
Content = "✕ Clear",
Padding = new Avalonia.Thickness(8, 4),
Background = Brushes.Transparent,
BorderThickness = new Avalonia.Thickness(0),
Foreground = Brushes.Red,
FontSize = 11,
Opacity = 0.7
};
clearBtn.Click += (s, e) => {
_recentCities.Clear();
if (File.Exists(_historyFile)) File.Delete(_historyFile);
UpdateHistoryUI();
};
HistoryPanel.Children.Add(clearBtn);
}
}
private async void OnSearchKeyDown(object? sender, KeyEventArgs e)
{
if (e.Key == Key.Enter || e.Key == Key.Return)
{
string city = CitySearch.Text?.Trim() ?? "";
if (!string.IsNullOrEmpty(city)) await PerformSearch(city);
}
}
private async Task PerformSearch(string city, bool isAutoRefresh = false)
{
_currentCity = city;
if (!isAutoRefresh) ConditionText.Text = "Fetching...";
try {
var geoUrl = $"https://nominatim.openstreetmap.org/search?q={Uri.EscapeDataString(city)}&format=json&limit=1";
var geoList = await http.GetFromJsonAsync(geoUrl, WeatherContext.Default.ListGeoResponse);
if (geoList != null && geoList.Count > 0) {
if (!isAutoRefresh) SaveCityToHistory(city);
double lat = double.Parse(geoList[0].lat, CultureInfo.InvariantCulture);
double lon = double.Parse(geoList[0].lon, CultureInfo.InvariantCulture);
await TryOpenMeteo(lat, lon);
} else if (!isAutoRefresh) {
ConditionText.Text = "City Not Found";
}
} catch {
if (!isAutoRefresh) ConditionText.Text = "Error Connecting";
}
}
private async Task<bool> TryOpenMeteo(double lat, double lon) {
try {
var url = $"https://api.open-meteo.com/v1/forecast?latitude={lat}&longitude={lon}¤t=temperature_2m,relative_humidity_2m,precipitation,weather_code,wind_speed_10m&hourly=temperature_2m,relative_humidity_2m,precipitation,precipitation_probability,weather_code&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum,precipitation_probability_max,sunrise,sunset&timezone=auto";
var res = await http.GetFromJsonAsync(url, WeatherContext.Default.OpenMeteoResponse);
if (res != null) {
// 1. Calculate Local Time using the UTC offset from the API
var localTime = DateTimeOffset.UtcNow.AddSeconds(res.utc_offset_seconds);
string timeString = localTime.ToString("HH:mm");
int currentChance = res.hourly.prob.Length > 0 ? res.hourly.prob[0] : 0;
string mainSunrise = DateTime.Parse(res.daily.sunrise[0]).ToString("HH:mm");
string mainSunset = DateTime.Parse(res.daily.sunset[0]).ToString("HH:mm");
TempText.Text = $"{(int)res.current.temperature}°";
HumText.Text = $"💧 {res.current.relative_humidity}% | 🌧️ {res.current.precipitation}mm | ☔ {currentChance}% | 💨 {res.current.windspeed}km/h\n🌅 {mainSunrise} | 🌇 {mainSunset}";
// 2. Display Description + Local Time
ConditionText.Text = $"{GetWeatherDescription(res.current.weather_code)} | {timeString}";
// Build Hourly (Next 24 Hours)
HourlyPanel.Children.Clear();
for (int i = 0; i < 24; i++) {
var time = DateTime.Parse(res.hourly.time[i]).ToString("HH:mm");
var info = $"{(int)res.hourly.temp[i]}° | 💧{res.hourly.humidity[i]}%\n☔{res.hourly.prob[i]}% | 🌧️{res.hourly.precip[i]}mm";
HourlyPanel.Children.Add(CreateSmallCard(time, GetWeatherIcon(res.hourly.weather_code[i]), info));
}
// Build Weekly (7-Day Outlook)
ForecastPanel.Children.Clear();
for (int i = 0; i < res.daily.time.Length; i++) {
var day = DateTime.Parse(res.daily.time[i]).ToString("ddd");
string sunRiseDaily = DateTime.Parse(res.daily.sunrise[i]).ToString("HH:mm");
string sunSetDaily = DateTime.Parse(res.daily.sunset[i]).ToString("HH:mm");
var info = $"{(int)res.daily.temp_max[i]}°/{(int)res.daily.temp_min[i]}°\n☔{res.daily.prob_max[i]}% | 🌧️{res.daily.prec_sum[i]}mm\n🌅{sunRiseDaily} 🌇{sunSetDaily}";
ForecastPanel.Children.Add(CreateSmallCard(day, GetWeatherIcon(res.daily.weather_code[i]), info));
}
return true;
}
} catch { }
return false;
}
private StackPanel CreateSmallCard(string top, string icon, string bottom) {
// Increased width slightly to fit the new sun times
var p = new StackPanel { Width = 145, Spacing = 2, Margin = new Avalonia.Thickness(5) };
p.Children.Add(new TextBlock {
Text = top,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
Foreground = Brushes.LightGray,
FontSize = 12
});
// FORCING WHITE COLOR HERE
p.Children.Add(new TextBlock {
Text = icon,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
FontSize = 28,
Foreground = Brushes.White // Explicitly set to bright white
});
p.Children.Add(new TextBlock {
Text = bottom,
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
Foreground = Brushes.White,
FontSize = 10,
TextAlignment = TextAlignment.Center
});
return p;
}
private string GetWeatherIcon(int code) => code switch {
0 => "☀️", 1 or 2 or 3 => "⛅", 45 or 48 => "🌫️",
51 or 53 or 55 => "🌦️", 61 or 63 or 65 => "🌧️",
71 or 73 or 75 => "❄️", 95 => "⛈️", _ => "☁️"
};
private string GetWeatherDescription(int code) => code switch {
0 => "Clear Sky", 1 or 2 or 3 => "Partly Cloudy", 95 => "Stormy", _ => "Cloudy"
};
}
// --- MODELS (REPLACE YOUR BOTTOM SECTION WITH THIS) ---
[JsonSerializable(typeof(List<GeoResponse>))]
[JsonSerializable(typeof(OpenMeteoResponse))]
internal partial class WeatherContext : JsonSerializerContext { }
// Combined into ONE record to avoid "Duplicate" errors
public record OpenMeteoResponse(
CurrentData current,
DailyData daily,
HourlyData hourly,
[property: JsonPropertyName("utc_offset_seconds")] int utc_offset_seconds
);
public record CurrentData(
[property: JsonPropertyName("temperature_2m")] double temperature,
[property: JsonPropertyName("relative_humidity_2m")] double relative_humidity,
[property: JsonPropertyName("precipitation")] double precipitation,
[property: JsonPropertyName("weather_code")] int weather_code,
[property: JsonPropertyName("wind_speed_10m")] double windspeed
);
public record DailyData(
string[] time,
[property: JsonPropertyName("weather_code")] int[] weather_code,
[property: JsonPropertyName("temperature_2m_max")] double[] temp_max,
[property: JsonPropertyName("temperature_2m_min")] double[] temp_min,
[property: JsonPropertyName("precipitation_sum")] double[] prec_sum,
[property: JsonPropertyName("precipitation_probability_max")] int[] prob_max,
string[] sunrise,
string[] sunset
);
public record HourlyData(
string[] time,
[property: JsonPropertyName("temperature_2m")] double[] temp,
[property: JsonPropertyName("relative_humidity_2m")] double[] humidity,
[property: JsonPropertyName("precipitation")] double[] precip,
[property: JsonPropertyName("precipitation_probability")] int[] prob,
[property: JsonPropertyName("weather_code")] int[] weather_code
);
public record GeoResponse(string lat, string lon);