package main

import (
	"machine"
	"machine/usb/hid/mouse"
	"time"
)

const DEADZONE = 5000

func main() {

	// 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{})

	// A = left click, B = right click
	btnA := machine.P1_06
	btnB := machine.P1_04
	btnA.Configure(machine.PinConfig{Mode: machine.PinInputPullup})
	btnB.Configure(machine.PinConfig{Mode: machine.PinInputPullup})

	mouseDevice := mouse.Port()

	for {
		// ADC center is ~32767; compute offset from center
		rawX := int(ax.Get()) - 32767
		rawY := int(ay.Get()) - 32767

		var dx, dy int
		if rawX > DEADZONE || rawX < -DEADZONE {
			dx = rawX / 2048
		}
		if rawY > DEADZONE || rawY < -DEADZONE {
			dy = rawY / 2048
		}

		mouseDevice.Move(dx, dy)

		if !btnA.Get() {
			mouseDevice.Click(mouse.Left)
		}
		if !btnB.Get() {
			mouseDevice.Click(mouse.Right)
		}

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