package gui

import (

	"github.com/gdamore/tcell/v2"
	"github.com/rivo/tview"
	"shiny-pancake/internal/model"
	"time"
)



type activeSessions struct {
	*tview.Table
	sn chan *model.Session
	filterCol, filterTerm string
}


func newSessions(g *Gui) *activeSessions {
	sess := &activeSessions{
		Table: tview.NewTable(),
		sn:  make(chan *model.Session),
	}

	sess.SetBorder(true)
	sess.entries(g)
	return sess
}

func (t *activeSessions) name() string {
	return `activeSessions`
}



func (t *activeSessions) entries(g *Gui) {
	sss, err := g.db.UserSessions()
	if err != nil {
		return
	}

	g.state.resources.ActSess = sss
}

func (t *activeSessions) setEntries(g *Gui) {
	t.entries(g)
	table := t.Clear()

	headers := []string{
		"user",
		"session count",
	}

	for i, header := range headers {
		table.SetCell(0, i, &tview.TableCell{
			Text:            header,
			NotSelectable:   true,
			Align:           tview.AlignLeft,
			Color:           tview.Styles.PrimaryTextColor,
			BackgroundColor: tview.Styles.PrimitiveBackgroundColor,
			Attributes:      tcell.AttrBold,
		})
	}

	for i, s := range g.state.resources.ActSess {
		table.SetCell(i+1, 0, tview.NewTableCell(s.Username).
			SetTextColor(tview.Styles.PrimaryTextColor).
			SetMaxWidth(30).
			SetExpansion(1))

		table.SetCell(i+1, 1, tview.NewTableCell(string(s.Count)).
			SetTextColor(tview.Styles.PrimaryTextColor).
			SetMaxWidth(30).
			SetExpansion(1))

	}
}

func (t *activeSessions) updateEntries(g *Gui) {
	g.app.QueueUpdateDraw(func() {
		t.setEntries(g)
	})
}

func (t *activeSessions) focus(g *Gui) {
	t.SetSelectable(true, false)
	g.app.SetFocus(t)
}

func (t *activeSessions) unfocus() {
	t.SetSelectable(false, false)
}

func (t *activeSessions) monitoringSessions(g *Gui) {
	ticker := time.NewTicker(5 * time.Minute)

LOOP:
	for {
		select {
		case <-ticker.C:
			t.updateEntries(g)
		case <-g.state.stopChans["trips"]:
			ticker.Stop()
			break LOOP
		}
	}
}
