package gui

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

	"shiny-pancake/internal/database"
	"strings"

	tview "gitlab.com/tslocum/cview"
)

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
	panels *tview.Panels
	state  *state
	db     *database.Database
}

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


// Start start application
func (g *Gui) Start() error {
	g.initPanels()
	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.app.Stop()
}

// Page "definitions"

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


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)

	/*
		// NOTE: I would really like to get this working as it would be far neater.
		// The issue is with the three panels being of different types.
		// cannot use pg (type panel) as type tview.Primitive in argument to g.panels.AddPage:
		// panel does not implement tview.Primitive (missing Blur method)
		for idx, pg := range []panel{trips, cavers, caves} {
			name := pg.name()
			g.panels.AddPage(name, pg, true, idx == 0)
			fmt.Fprintf(g.state.tabBar, ` %d ["%d"][darkcyan]%s[white][""]  `, idx+1, idx, strings.Title(name))
		}
		g.state.tabBar.Highlight("0")
	*/

	// Add panels to the "book"
	g.panels.AddPanel(`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)


	g.app.SetRoot(g.panels, true)
}
