package look

import (
	//"database/sql"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/glamour"
	"github.com/charmbracelet/bubbles/viewport"
	"github.com/muesli/termenv"
	tp "pgm/templates"
	"encoding/json"
	"fmt"
	"github.com/spf13/viper"
	"io/ioutil"
	//"log"
	"pgm/data"
	//db2 "pgm/db"
	"pgm/logger"
	"time"
	//"os"
)

var term = termenv.ColorProfile()

var (
	columns = []string{"name", "company"}
	rows = []string{"bob", "fart co"}
	colCt = 2
	sql_test = "SELECT usename, count(usename) FROM pg_stat_activity where usename is not null group by usename"
)

type tickMsg time.Time


func (e screen) Init() tea.Cmd {
	return nil
}


type screen struct {
	viewport viewport.Model
}

// the default view for a user once they load a database is called the look.
// the look loads
func Look(f string) {
	var connectionDetails data.HostDetails
	connectionDetails = loadHost(f)
	_ = connectionDetails


	var t tp.Tbl
	t = tp.Tbl{columns, colCt, rows, ""}
	tp.Table(t)



	//model, err := newExample()
	//if err != nil {
	//	fmt.Println("Could not intialize Bubble Tea model:", err)
	//	os.Exit(1)
	//}
	//
	//if err := tea.NewProgram(model).Start(); err != nil {
	//	fmt.Println("Bummer, there's been an error:", err)
	//	os.Exit(1)
	//}


}

func (e screen) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		e.viewport.Width = msg.Width
		return e, nil

	case tea.KeyMsg:
		switch msg.String() {
		case "q", "ctrl+c":
			return e, tea.Quit
		default:
			vp, _ := viewport.Update(msg, e.viewport)
			e.viewport = vp
		}
	}

	return e, nil
}

func (e screen) View() string {
	return viewport.View(e.viewport) + e.helpView()
}

func (e screen) helpView() string {
	return termenv.String("\n  ↑/↓: Navigate • q: Quit\n").Foreground(term.Color("241")).String()
}



func newExample() (*screen, error) {
	vp := viewport.Model{Width: 78, Height: 10}
	renderer, err := glamour.NewTermRenderer(glamour.WithStylePath("notty"))
	if err != nil {
		return nil, err
	}

	var t tp.Tbl
	t = tp.Tbl{columns, colCt, rows, ""}
	tp.Table(t)


	str, err := renderer.Render(t.View)
	if err != nil {
		return nil, err
	}

	vp.SetContent(str)

	return &screen{
		viewport: vp,
	}, nil
}



// gets information for host from hostDir
func loadHost(f string) data.HostDetails {
	var hostDir string
	hostDir = viper.GetString("hostsDir")
	file, _ := ioutil.ReadFile(hostDir + "/"+ f)

	data := data.HostDetails{}

	err := json.Unmarshal(file, &data)
	if err != nil {
		logger.Logger("[ERROR] error loading host, malformed file: " +  f)
		logdir := viper.GetString("logsDir")
		fmt.Println("fatal error occured, see logs at " + logdir)
	}
	return data
}