package radar_lib

import (
	"log"
)

func (r *Radar) listenSerial() {
	rcvBuf := make([]byte, 100)
	lastIndex := 0
	for {
		buf := make([]byte, 100)
		n, err := r.port.Read(buf)
		if err != nil {
			log.Fatal(err)
			break
		}
		if n == 0 {
			log.Println("\nEOF")
			break
		}
		for i := 0; i < n; i++ {
			rcvBuf[lastIndex] = buf[i]
			if i > 1 && buf[i-1] == 0x0D && buf[i] == 0x0A {
				r.decodeInput(rcvBuf[0 : lastIndex+1])
				lastIndex = 0
			} else {
				lastIndex++
			}
		}
	}
}

func (r *Radar) decodeInput(buf []byte) {
	// trigger message
	if len(buf) > 2 && buf[0] == 0x56 && buf[1] == 0x50 {
		log.Printf("Radar Trigger Message Event %d", buf[2])
		return
	}
	// config response
	if len(buf) > 2 && buf[0] == 0x46 && buf[1] == 0x43 {
		s := "FAIL"
		if buf[3] == 0 {
			s = "SUCCESS"
		}
		log.Printf("%s response: Code: %d", s, buf[2])
		return
	}
	// speed information
	if len(buf) > 2 && buf[0] == 0x56 && buf[1] == 0x52 {
		dir := "incoming"
		if buf[2]&(1<<(6)) != 0 {
			dir = "outgoing"
		}
		overspeed := "no"
		if buf[2]&(1<<(3)) == 1 {
			overspeed = "yes"
		}
		valid := "no"
		if buf[2]&(1<<(0)) == 1 {
			valid = "yes"
		}
		log.Printf("Speed: %dkm/h (%s, Over: %s, Valid: %s)", buf[3], dir, overspeed, valid)
		if r.speedHandler != nil {
			r.speedHandler(int(buf[3]))
		} else {
			log.Printf("speedhandler = nil")
		}
		if overspeed == "yes" && valid == "yes" && r.handler != nil {
			r.handler(int(buf[3]))
		}
		return
	}
	// skip this for now
	if len(buf) > 2 && buf[0] == 0x56 && buf[1] == 0x51 {

		return
	}

	log.Printf("%# x\n", buf)
}
