github.com/wtfutil/wtf@v0.43.0/modules/krisinformation/widget.go (about)

     1  package krisinformation
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/rivo/tview"
     8  	"github.com/wtfutil/wtf/view"
     9  )
    10  
    11  // Widget is the container for your module's data
    12  type Widget struct {
    13  	view.TextWidget
    14  
    15  	app      *tview.Application
    16  	settings *Settings
    17  	err      error
    18  	client   *Client
    19  }
    20  
    21  // NewWidget creates and returns an instance of Widget
    22  func NewWidget(app *tview.Application, redrawChan chan bool, settings *Settings) *Widget {
    23  	widget := Widget{
    24  		TextWidget: view.NewTextWidget(app, redrawChan, nil, settings.common),
    25  		app:        app,
    26  		settings:   settings,
    27  		client: NewClient(
    28  			settings.latitude,
    29  			settings.longitude,
    30  			settings.radius,
    31  			settings.county,
    32  			settings.country),
    33  	}
    34  
    35  	return &widget
    36  }
    37  
    38  /* -------------------- Exported Functions -------------------- */
    39  
    40  // Refresh updates the onscreen contents of the widget
    41  func (widget *Widget) Refresh() {
    42  	if widget.Disabled() {
    43  		return
    44  	}
    45  	// The last call should always be to the display function
    46  	widget.display()
    47  }
    48  
    49  /* -------------------- Unexported Functions -------------------- */
    50  
    51  func (widget *Widget) content() (string, string, bool) {
    52  	var title = defaultTitle
    53  	if widget.CommonSettings().Title != "" {
    54  		title = widget.CommonSettings().Title
    55  	}
    56  	now := time.Now()
    57  	kriser, err := widget.client.getKrisinformation()
    58  	if err != nil {
    59  		handleError(widget, err)
    60  	}
    61  
    62  	var str string
    63  	i := 0
    64  	for k := range kriser {
    65  		diff := now.Sub(kriser[k].Updated)
    66  		if widget.settings.maxage != -1 {
    67  			// Skip if message is too old
    68  			if int(diff.Hours()) > widget.settings.maxage {
    69  				//logger.Log(fmt.Sprintf("Article to old: (%s) Days: %d", kriser[k].HeadLine, int(diff.Hours())))
    70  				continue
    71  			}
    72  		}
    73  		i++
    74  		if i > widget.settings.maxitems && widget.settings.maxitems != -1 {
    75  			break
    76  		}
    77  		str += fmt.Sprintf("- %s\n", kriser[k].HeadLine)
    78  	}
    79  	return title, str, true
    80  }
    81  
    82  func (widget *Widget) display() {
    83  	widget.Redraw(func() (string, string, bool) {
    84  		return widget.content()
    85  	})
    86  }
    87  
    88  func handleError(widget *Widget, err error) {
    89  	widget.err = err
    90  }