forked from wtfutil/wtf
/
widget.go
109 lines (84 loc) · 2.45 KB
/
widget.go
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
package weather
import (
owm "github.com/briandowns/openweathermap"
"github.com/rivo/tview"
"github.com/doctorfree/wtf/utils"
"github.com/doctorfree/wtf/view"
)
// Widget is the container for weather data.
type Widget struct {
view.MultiSourceWidget
view.TextWidget
// APIKey string
Data []*owm.CurrentWeatherData
pages *tview.Pages
settings *Settings
}
// NewWidget creates and returns a new instance of the weather Widget
func NewWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, settings *Settings) *Widget {
widget := Widget{
MultiSourceWidget: view.NewMultiSourceWidget(settings.Common, "cityid", "cityids"),
TextWidget: view.NewTextWidget(tviewApp, redrawChan, pages, settings.Common),
pages: pages,
settings: settings,
}
widget.initializeKeyboardControls()
widget.SetDisplayFunction(widget.display)
return &widget
}
/* -------------------- Exported Functions -------------------- */
// Fetch retrieves OpenWeatherMap data from the OpenWeatherMap API.
// It takes a list of OpenWeatherMap city IDs.
// It returns a list of OpenWeatherMap CurrentWeatherData structs, one per valid city code.
func (widget *Widget) Fetch(cityIDs []int) []*owm.CurrentWeatherData {
data := []*owm.CurrentWeatherData{}
for _, cityID := range cityIDs {
result, err := widget.currentWeather(cityID)
if err == nil {
data = append(data, result)
}
}
return data
}
// Refresh fetches new data from the OpenWeatherMap API and loads the new data into the.
// widget's view for rendering
func (widget *Widget) Refresh() {
if widget.apiKeyValid() {
widget.Data = widget.Fetch(utils.ToInts(widget.settings.cityIDs))
}
widget.display()
}
/* -------------------- Unexported Functions -------------------- */
func (widget *Widget) apiKeyValid() bool {
if widget.settings.apiKey == "" {
return false
}
if len(widget.settings.apiKey) != 32 {
return false
}
return true
}
func (widget *Widget) currentData() *owm.CurrentWeatherData {
if len(widget.Data) == 0 {
return nil
}
if widget.Idx < 0 || widget.Idx >= len(widget.Data) {
return nil
}
return widget.Data[widget.Idx]
}
func (widget *Widget) currentWeather(cityCode int) (*owm.CurrentWeatherData, error) {
weather, err := owm.NewCurrent(
widget.settings.tempUnit,
widget.settings.language,
widget.settings.apiKey,
)
if err != nil {
return nil, err
}
err = weather.CurrentByID(cityCode)
if err != nil {
return nil, err
}
return weather, nil
}