Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
gRPCStatusView.go 1.61 KiB
package views

import (
	"code.fbi.h-da.de/cocsn/gosdn/cmd/gosdn-tview/app"
	"github.com/rivo/tview"
	"google.golang.org/grpc"
	"time"
)

//GRPCStatusView is an application view to display the current status of
//the gRPC server (e.g. connected, unavailable,...)
type GRPCStatusView struct {
	gRPCStatusView *tview.TextView
}

//NewGRPCStatusView creates a new GRPCStatusView
func NewGRPCStatusView(app *app.App, conn *grpc.ClientConn) *GRPCStatusView {
	sv := &GRPCStatusView{
		gRPCStatusView: tview.NewTextView(),
	}

	sv.gRPCStatusView.
		SetDynamicColors(true).
		SetTextAlign(tview.AlignCenter).
		SetRegions(true).
		SetBorder(true).
		SetTitle("gRPC")

	//TODO: gRPCs Health Check looks like a way better alternative here!
	//--> no app.Draw() required anymore
	sv.gRPCStatusView.SetChangedFunc(func() {
		app.Draw()
	})

	go gRPCTicker(sv, conn)

	return sv
}

//GetContent returns the tview.Primitive belonging to the gRPCStatusView
func (sv *GRPCStatusView) GetContent() tview.Primitive {
	return sv.gRPCStatusView
}

//SetContent sets new string content for the gRPCStatusView
func (sv *GRPCStatusView) SetContent(s string) {
	sv.gRPCStatusView.Clear()
	sv.gRPCStatusView.SetText(s)
}

func gRPCTicker(sv *GRPCStatusView, conn *grpc.ClientConn) {
	sv.SetContent(checkStatus(conn))
	//TODO: refactor -> get rid of hardcoded values
	ticker := time.NewTicker(5 * time.Second)
	for range ticker.C {
		sv.SetContent(checkStatus(conn))
	}
}

func checkStatus(conn *grpc.ClientConn) string {
	if str := conn.GetState().String(); str == "READY" || str == "IDLE" {
		return "[green]" + "connected"
	} else {
		return "[red]" + "disconnected"
	}
}