package main

import (
	"log"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"

	_ "embed"
)

type ActionConfig struct {
	username string
	password string
	hostname string
	port     int
}

const (
	appName string = "Systemec RaspScreen"
)

var (
	windowSize  fyne.Size = fyne.NewSize(750, 700) // Default Window size
	buttonSize  fyne.Size = fyne.NewSize(200, 50)  // Default button size
	dButtonSize fyne.Size = fyne.NewSize(150, 50)  // Button size for upload & reload
	entrySize   fyne.Size = fyne.NewSize(200, 40)
)

func main() {
	cfg := readConfig()

	iconResource := fyne.NewStaticResource("./src/icon.ico", iconData)
	//iconResource, _ := fyne.LoadResourceFromURLString("https://www.systemec.nl/favicon.ico")
	//iconResource, _ := fyne.LoadResourceFromPath("./icon.ico")

	app := app.NewWithID("nl.systemec.raspscreen")
	app.Settings().SetTheme(theme.DefaultTheme())
	app.SetIcon(iconResource)

	w := app.NewWindow(appName)
	w.Resize(windowSize)
	w.SetIcon(iconResource)

	raspiNames := getRaspiNames(cfg)

	// Define variables and print them out for debug
	// Presentation = 1
	// Video = 2
	var targetMode int = 0
	var raspiTarget string = ""
	var localUploadPath string

	log.Println("Current mode:", targetMode)
	if raspiTarget == "" {
		log.Println("Current target: None")
	} else {
		log.Println("Current target:", raspiTarget)
	}

	// Call the draw functions -> ./src/draw.go
	footerRow, uploadBtn, reloadBtn := drawFooter(app, &raspiTarget, &localUploadPath, &targetMode, cfg)
	modeBtnRow := drawModeRow(&targetMode)
	selectionRow := drawTargetSection(raspiNames, &raspiTarget, uploadBtn, reloadBtn, cfg)
	fileSelectRow := drawFileSelection(&localUploadPath, &targetMode, w)

	center := container.NewVBox(
		modeBtnRow,
		widget.NewLabel(""),
		fileSelectRow,
		drawSeparator(true, true),
		selectionRow,
	)

	top := container.NewVBox(
		widget.NewLabel(appName),
		drawSeparator(false, false),
	)

	content := container.NewBorder(
		top,       // top
		footerRow, // bottom
		nil, nil,  // left, right
		center, //center
	)

	w.SetContent(content)
	w.ShowAndRun()
}

func refreshButtons(givenButtons ...*widget.Button) {
	for _, b := range givenButtons {
		btn := b
		fyne.CurrentApp().Driver().DoFromGoroutine(func() {
			btn.Refresh()
		}, false)
	}
}

// The raspiList is defined in the other go file, must me maintained separately
func getRaspiNames(cfg RaspiConfig) []string {
	raspiNames := make([]string, 0, len(cfg.Raspis))

	// Append the name of the pi to the list we need for the radio button
	// i is the index field correlated to the name as per defined in rpi-list.go
	for _, n := range cfg.Raspis {
		raspiNames = append(raspiNames, n.Name) // append only the first element
	}

	return raspiNames
}
