package config

import (
	"odoki/comms"
	"odoki/constants"
	"odoki/ui/components"
	"slices"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"tinygo.org/x/bluetooth"
)

type data struct {
	discoveredAdresses []bluetooth.Address
}

var appdata data

func handleDeviceDiscovered(selectWidget *widget.Select, adapter *bluetooth.Adapter, device bluetooth.ScanResult) {
	//println("found device:", device.Address.String(), device.RSSI, device.LocalName())
	stylizedName := "(" + device.LocalName() + ")[" + device.Address.String() + "]"
	if !slices.Contains(appdata.discoveredAdresses, device.Address) {
		selectWidget.Options = append(selectWidget.Options, stylizedName)
		appdata.discoveredAdresses = append(appdata.discoveredAdresses, device.Address)
	}
}

func Widget() fyne.CanvasObject {
	connectionStatus := canvas.NewText("Connection status: Disconnected", theme.ForegroundColor())
	devicesSelection := widget.NewSelect([]string{}, func(string) {})
	scanButton := widget.NewButton("Scan", func() {
		appdata.discoveredAdresses = []bluetooth.Address{}
		go comms.Scan(devicesSelection, handleDeviceDiscovered)
	})
	scanContainer := container.New(layout.NewFormLayout(), scanButton, devicesSelection)
	return container.NewPadded(container.NewVBox(
		components.TabTitle("Config"),
		connectionStatus,
		scanContainer,
		widget.NewButton("Connect", func() {
			if len(appdata.discoveredAdresses) != 0 {
				comms.Connect(appdata.discoveredAdresses[devicesSelection.SelectedIndex()])
				if comms.Connected {
					connectionStatus.Text = "Connection status: Connected"
					connectionStatus.Color = constants.SuccessColor
				} else {
					connectionStatus.Text = "Connection status: Connection error"
					connectionStatus.Color = constants.ErrorColor
				}
			} else {
				connectionStatus.Text = "Connection status: No devices found yet!"
				connectionStatus.Color = constants.ErrorColor
			}
			connectionStatus.Refresh()
		}),
	))
}
