package lbsmultibase

import (
	"encoding/binary"
	"fmt"
	"primesys_producer/src/logger"
	"primesys_producer/src/protocol/crc"
	"primesys_producer/src/server/frame"
	. "primesys_producer/src/types"
)

// Protocol number 0x28

type LBSMultibaseInformationPacket struct {
	SerialNumber uint16
}

func DecodeLBSMultiBasePacket(fr frame.Frame) (LBSMultibaseInformationPacket, error) {

	body := fr.Body()
	const expectedLen = 38
	if len(body) < expectedLen {
		logger.Error("Bytes of LBS Information packet is not complete %d", len(body))
		return LBSMultibaseInformationPacket{}, fmt.Errorf("Expected Len does not match ex : %d body: %d", expectedLen, len(body))
	}

	serial := binary.BigEndian.Uint16(fr.SerialNumber())

	return LBSMultibaseInformationPacket{
		SerialNumber: serial,
	}, nil
}

func EncodeLBSMultiBaseInformationPacket(serial uint16, protocolNumber ProtocolNumber) []byte {
	const requiredLen = 5
	s1 := byte(serial >> 8)
	s2 := byte(serial)
	crcInput := []byte{requiredLen, byte(protocolNumber), s1, s2}
	hi, lo := crc.CRC16X25Bytes(crcInput)
	ack := make([]byte, 0)
	ack = append(ack, StartShortByte, StartShortByte, requiredLen, byte(protocolNumber), s1, s2, hi, lo, StopByte1, StopByte2)
	return ack
}
