-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProcessQuery.cs
93 lines (81 loc) · 3 KB
/
ProcessQuery.cs
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
using cweather.WeatherData;
using cweather.LocationData;
using cweather.ApiClient;
using System.Threading.Tasks;
using System;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using Spectre.Console;
namespace cweather
{
public class ProcessQuery
{
private JObject _weatherJsonObject;
private Weather _weather;
public Weather Weather => _weather;
private Location _location;
public Location Location => _location;
private readonly SimpleMapBoxApiClient _mpApi;
private readonly OpenWeatherApiClient _opApi;
private readonly string _queryLoc;
public ProcessQuery(string queryLoc)
{
_queryLoc = queryLoc;
_mpApi = new SimpleMapBoxApiClient();
_opApi = new OpenWeatherApiClient();
}
// get the location
private async Task GetLocationAsync()
{
var res = await _mpApi.GetLatLongAsync(_queryLoc);
_location = new Location(res);
}
// get the weather
private async Task GetWeatherJsonAsync()
{
_weatherJsonObject = await _opApi.GetWeatherAsync(_location);
}
// preocess the weather data
public async Task ProcessWeatherData()
{
// show a fancy spinner while the data is fetched from the API
await AnsiConsole.Status()
.StartAsync("Fetching Data... ", async ctx =>
{
ctx.Spinner(Spinner.Known.Dots2);
await GetLocationAsync();
await GetWeatherJsonAsync();
});
// Parsing the current weather data
var currentWeather = new CurrentWeather(_weatherJsonObject.SelectToken("current"));
// Parsing the hourly weather data
var hourlyWeathers = ProcessData(
_weatherJsonObject.SelectToken("hourly"),
(tempTok) => new HourlyWeather(tempTok)
);
// parsing the daily weather
var dailyWeathers = ProcessData(
_weatherJsonObject.SelectToken("daily"),
(tempTok) => new DailyWeather(tempTok)
);
// Combining all the data in a single object that (nearly) represents JSON object
_weather = new Weather(
_weatherJsonObject.SelectToken("timezone").ToString(),
currentWeather,
dailyWeathers,
hourlyWeathers
);
}
// A generic method to parse various forms of data from the JToken
private static List<T> ProcessData<T>(JToken hourlyTok, Func<JToken, T> consFunc)
{
var dataList = new List<T>();
foreach (var item in hourlyTok)
{
var temp = consFunc(item);
dataList.Add(temp);
}
return dataList;
}
}
}