package main

import (
	"image/color"
	"machine"
	"time"

	"tinygo.org/x/drivers/st7789"
	"tinygo.org/x/tinydraw"
)

func main() {
	machine.SPI0.Configure(machine.SPIConfig{
		SCK:       machine.P1_01,
		SDO:       machine.P1_02,
		Frequency: 8000000,
		Mode:      0,
	})

	display := st7789.New(machine.SPI0,
		machine.P1_15, // TFT_RESET
		machine.P1_13, // TFT_DC
		machine.P0_10, // TFT_CS
		machine.P0_09) // TFT_LITE

	display.Configure(st7789.Config{
		Rotation:     st7789.ROTATION_90,
		Width:        135,
		Height:       240,
		RowOffset:    40,
		ColumnOffset: 53,
	})

	// joystick analog axes
	machine.InitADC()
	ax := machine.ADC{Pin: machine.P0_02} // X axis
	ay := machine.ADC{Pin: machine.P0_29} // Y axis
	ax.Configure(machine.ADCConfig{})
	ay.Configure(machine.ADCConfig{})

	black := color.RGBA{0, 0, 0, 255}
	dot := color.RGBA{0, 255, 100, 255}

	display.FillScreen(black)

	var prevX, prevY int16
	for {
		// ADC returns 0-65535; map to display dimensions (240x135)
		// -1 to avoid overflow
		dotX := int16(uint32(ax.Get()-1) * 240 / 65535)
		dotY := int16(uint32(-ay.Get()-1) * 135 / 65535)

		// erase previous dot
		tinydraw.FilledCircle(&display, prevX, prevY, 5, black)

		// draw new dot
		tinydraw.FilledCircle(&display, dotX, dotY, 5, dot)

		prevX = dotX
		prevY = dotY

		time.Sleep(30 * time.Millisecond)
	}
}
