github.com/wtfutil/wtf@v0.43.0/modules/covid/widget.go (about) 1 package covid 2 3 import ( 4 "fmt" 5 6 "github.com/rivo/tview" 7 "github.com/wtfutil/wtf/view" 8 ) 9 10 // Widget is the struct that defines this module widget 11 type Widget struct { 12 view.TextWidget 13 14 settings *Settings 15 err error 16 } 17 18 // NewWidget creates a new widget for this module 19 func NewWidget(app *tview.Application, redrawChan chan bool, settings *Settings) *Widget { 20 widget := &Widget{ 21 TextWidget: view.NewTextWidget(app, redrawChan, nil, settings.Common), 22 23 settings: settings, 24 } 25 26 widget.View.SetScrollable(true) 27 28 return widget 29 } 30 31 // Refresh checks if this module widget is disabled 32 func (widget *Widget) Refresh() { 33 if widget.Disabled() { 34 return 35 } 36 37 widget.Redraw(widget.content) 38 } 39 40 // Render renders this module widget 41 func (widget *Widget) Render() { 42 widget.Redraw(widget.content) 43 } 44 45 // Display stats based on the user's locale 46 func (widget *Widget) displayStats(cases int) string { 47 prntr, err := widget.settings.LocalizedPrinter() 48 if err != nil { 49 return err.Error() 50 } 51 52 return prntr.Sprintf("%d", cases) 53 } 54 55 func (widget *Widget) content() (string, string, bool) { 56 title := defaultTitle 57 if widget.CommonSettings().Title != "" { 58 title = widget.CommonSettings().Title 59 } 60 61 cases, err := LatestCases() 62 var covidStats string 63 if err != nil { 64 widget.err = err 65 } else { 66 // Display global stats 67 covidStats = fmt.Sprintf("[%s]Global[white]\n", widget.settings.Colors.Subheading) 68 covidStats += fmt.Sprintf("%s: %s\n", "Confirmed", widget.displayStats(cases.Latest.Confirmed)) 69 covidStats += fmt.Sprintf("%s: %s\n", "Deaths", widget.displayStats(cases.Latest.Deaths)) 70 } 71 // Retrieve country stats if country codes are set in the config 72 if len(widget.settings.countries) > 0 { 73 countryCases, err := widget.LatestCountryCases(widget.settings.countries) 74 if err != nil { 75 widget.err = err 76 } else { 77 for i, name := range countryCases { 78 covidStats += fmt.Sprintf("[%s]Country[white]: %s\n", widget.settings.Colors.Subheading, widget.settings.countries[i]) 79 covidStats += fmt.Sprintf("%s: %s\n", "Confirmed", widget.displayStats(name.Latest.Confirmed)) 80 covidStats += fmt.Sprintf("%s: %s\n", "Deaths", widget.displayStats(name.Latest.Deaths)) 81 } 82 } 83 } 84 85 return title, covidStats, true 86 }