package mloco

import (
	"encoding/binary"
	"fmt"
	"io"
)

const packetHeaderSize = 22

type packetHeader struct {
	ID        uint32
	Status    uint16
	Method    string
	bodyType  byte
	bodyLen   uint32
	rawMethod [11]byte
}

func parsePacketHeader(b []byte) (packetHeader, error) {
	if len(b) < packetHeaderSize {
		return packetHeader{}, fmt.Errorf("packet header too short: %d", len(b))
	}
	methodStart := 6
	methodEnd := methodStart
	for methodEnd < methodStart+11 && b[methodEnd] != 0x00 {
		methodEnd++
	}
	h := packetHeader{
		ID:       binary.LittleEndian.Uint32(b[0:4]),
		Status:   binary.LittleEndian.Uint16(b[4:6]),
		Method:   string(b[methodStart:methodEnd]),
		bodyType: b[17],
		bodyLen:  binary.LittleEndian.Uint32(b[18:22]),
	}
	copy(h.rawMethod[:], b[6:17])
	return h, nil
}

func (h packetHeader) encode() []byte {
	b := make([]byte, packetHeaderSize)
	binary.LittleEndian.PutUint32(b[0:4], h.ID)
	binary.LittleEndian.PutUint16(b[4:6], h.Status)
	methodBytes := []byte(h.Method)
	copy(b[6:17], methodBytes)
	b[17] = h.bodyType
	binary.LittleEndian.PutUint32(b[18:22], h.bodyLen)
	return b
}

func (h packetHeader) validate() error {
	if h.Status != 0 {
		return fmt.Errorf("packet status error: %d", h.Status)
	}
	return nil
}

type packet struct {
	header packetHeader
	body   []byte
}

func (p *packet) encode() []byte {
	out := make([]byte, 0, packetHeaderSize+len(p.body))
	out = append(out, p.header.encode()...)
	out = append(out, p.body...)
	return out
}

func readPacket(r io.Reader) (packet, error) {
	headerBytes := make([]byte, packetHeaderSize)
	if _, err := io.ReadFull(r, headerBytes); err != nil {
		return packet{}, err
	}
	header, err := parsePacketHeader(headerBytes)
	if err != nil {
		return packet{}, err
	}
	if header.bodyLen > 64*1024*1024 {
		return packet{}, fmt.Errorf("packet body too large: %d", header.bodyLen)
	}
	body := make([]byte, header.bodyLen)
	if _, err := io.ReadFull(r, body); err != nil {
		return packet{}, err
	}
	return packet{header: header, body: body}, nil
}
