package ecg

import (
	"odoki-firmware/ads1293"
	"odoki-firmware/constants"

	"machine"

	"tinygo.org/x/drivers"
)

var device ads1293.Device
var buffers [constants.ChannelCount][constants.BufferSize]int32
var bufferIndex uint32

var DisplayBuffers [constants.ChannelCount][constants.DisplayECGBufferSize]int32
var displayBufferInternalIndex int16
var DisplayBufferIndex int16

var HeartRate uint8 = 0

func Init(drdyPin, csPin machine.Pin, spiBus drivers.SPI) {
	device = ads1293.New(ads1293.Config{
		DrdyPin: drdyPin,
		CsPin:   csPin,
		SPIBus:  spiBus,
	})
	device.SetAds1293Pins()
	device.Ads1293Begin3LeadECG()
}

func HandleData(p machine.Pin) {
	ready, ecgCh1, ecgCh2, ecgCh3 := device.ReadChannelsIfReady()
	if ready {
		buffers[0][bufferIndex] = ecgCh1
		buffers[1][bufferIndex] = ecgCh2
		buffers[2][bufferIndex] = ecgCh3
		bufferIndex++

		displayBufferInternalIndex++
		if displayBufferInternalIndex == constants.DisplayECGRecEvery-1 {
			//comms.WriteECG(ecgCh1)
			displayBufferInternalIndex = 0
			DisplayBuffers[0][DisplayBufferIndex] = ecgCh1
			DisplayBuffers[1][DisplayBufferIndex] = ecgCh2
			DisplayBuffers[2][DisplayBufferIndex] = ecgCh3
			DisplayBufferIndex++
		}

		if DisplayBufferIndex == constants.DisplayECGBufferSize {
			DisplayBufferIndex = 0
		}

		if bufferIndex == constants.BufferSize-1 {
			bufferIndex = 0
		}

	}
}

func SetReadoutInterrupt() {
	device.DrdyPin.SetInterrupt(machine.PinFalling, HandleData)
}
