package main

import (
	"encoding/hex"
	"fmt"
	"log"
	"time"

	"github.com/go-daq/canbus"
)

func convertBytesToInt(frame []byte) uint64 {
	hexString := fmt.Sprintf("%x", frame)
	fmt.Println("Received CAN message:", hexString)

	parsedInt, err := hex.DecodeString(hexString)
	if err != nil {
		log.Fatalf("Error parsing hexadecimal string: %v", err)
	}
	var number uint64
	for i := 0; i < len(parsedInt); i++ {
		number = number*256 + uint64(parsedInt[i])
	}
	return number
}

func main() {
	// Creates a new CAN bus device socket
	canBus, err := canbus.New()
	if err != nil {
		log.Fatalf("Failed to open CAN bus: %v", err)
	}
	defer canBus.Close()

	err = canBus.Bind("can1")
	if err != nil {
		log.Fatalf("Failed to bind CAN socket to interface: %v", err)
	}

	// Receive CAN frames
	for {
		frame, err := canBus.Recv()
		time.Sleep(1 * time.Second)
		if err != nil {
			log.Fatalf("Cannot receive frame: %+v", err)
		}

		// Extract and print the number from the received frame
		scannedNumber := convertBytesToInt(frame.Data)
		fmt.Printf("Scanned QR number: %d\n", scannedNumber)
		print("\n")
	}
}
