package onlinecommand

// Protocol no 0x81
// command from terminal

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

type OnlineCommandTerminalPacket struct {
	CommandLength      uint16
	ServerFlag         string
	Content            string
	DecodedContent     string
	LaguageReserveByte []byte
	Serial             uint16
}

func DecodeOnlineCommandTerminalPacket(fr frame.Frame) (OnlineCommandTerminalPacket, error) {

	const expectedLen = 15
	body := fr.Body()

	if len(body) < expectedLen {
		logger.Error("Error in return packet from terminal of online command")
		return OnlineCommandTerminalPacket{}, fmt.Errorf("Length of terminal packet and expected did not match Error Packet: body: %d , expected: %d", len(body), expectedLen)
	}

	logger.Info("Debug Online Command %s", utils.HexUpper(fr.Raw))

	indexStart := 2
	var commndlen uint16 = 0

	if fr.PacketStartLength() == int8(PacketLong) {
		indexStart = 3
		commndlen = binary.BigEndian.Uint16(body[1:indexStart])

	} else {
		commndlen = uint16(body[1])
	}

	serverflag := body[indexStart : indexStart+4]
	indexStart = indexStart + 4
	content := body[indexStart : len(body)-6]
	serial := binary.BigEndian.Uint16(fr.SerialNumber())
	lang := body[len(body)-6 : len(body)-4]

	byteToStringContent := utils.ByteToString(content)
	decodedContent := string(byteToStringContent)

	return OnlineCommandTerminalPacket{
		CommandLength:      uint16(commndlen),
		Serial:             serial,
		ServerFlag:         utils.HexUpper(serverflag),
		Content:            byteToStringContent,
		DecodedContent:     decodedContent,
		LaguageReserveByte: lang,
	}, nil
}

func DecodeOnlineCommandServerFlag(fr frame.Frame) (string, error) {
	const expectedLen = 15
	body := fr.Body()

	if len(body) < expectedLen {
		logger.Error("Error in return packet from terminal of online command")
		return "", fmt.Errorf("Length of terminal packet and expected did not match Error Packet: body: %d , expected: %d", len(body), expectedLen)
	}

	indexStart := 2

	if fr.PacketStartLength() == int8(PacketLong) {
		indexStart = 3
	}
	serverflag := body[indexStart : indexStart+4]

	return utils.HexUpper(serverflag), nil
}
