package gui

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"shiny-pancake/internal/model"
	"shiny-pancake/logger"


	"shiny-pancake/internal/database"
	"strings"
	"github.com/rivo/tview"
)

type resources struct {
	ActSess          []*model.Session
}


type panels struct {
	currentPanel int
	panel        []panel
}


type state struct {
	panels    panels
	tabBar    *tview.TextView
	resources resources
	stopChans map[string]chan int
}

func newState() *state {
	return &state{
		stopChans: make(map[string]chan int),
	}
}

type Gui struct {
	app    *tview.Application
	pages *tview.Pages
	state  *state
	db     *database.Database
}

func New(db *database.Database) *Gui {
	return &Gui{
		app:    tview.NewApplication(),
		pages: tview.NewPages(),
		state:  newState(),
		db:     db,
	}
}


func (g *Gui) sessionPanel() *activeSessions {
	for _, panel := range g.state.panels.panel {
		if panel.name() == `activeSessions` {
			return panel.(*activeSessions)
		}
	}
	return nil
}

// Start start application
func (g *Gui) Start() error {
	g.initPanels()
	g.startMonitoring()
	var l logger.Log
	l = logger.Log{"info", logrus.Fields{"init" : "ran"}, "got this far"}
	logger.Lgr(&l)
	if err := g.app.Run(); err != nil {
		g.app.Stop()
		return err
	}

	return nil
}

func (g *Gui) Stop() {
	g.stopMonitoring()
	g.app.Stop()
}

// Page "definitions"



func (g *Gui) initPanels() {

	g.state.tabBar = newTabBar()
	// Page definitions
	s  := newSessions(g)

	var l logger.Log
	l = logger.Log{"info", logrus.Fields{"initPanels" : "ran"}, "got this far"}
	logger.Lgr(&l)


	g.pages.AddPage(`activeSessions`, s, true, true)
	fmt.Fprintf(g.state.tabBar, `  ["%d"]%d %s[""] `, 0, 1, strings.Title(s.name()))

	g.state.tabBar.Highlight("0")

	// Panels

	g.state.panels.panel = append(g.state.panels.panel, s)

	layout := tview.NewFlex().SetDirection(tview.FlexRow).
		AddItem(g.state.tabBar, 1, 1, false).
		AddItem(g.pages, 0, 16, true)

	g.app.SetRoot(layout, true)
	g.goTo(`activeSessions`)
}

func (g *Gui) goTo(page string) {
	g.pages.SwitchToPage(page)
}

