package bx

import (
	"bytes"
	"encoding/binary"
)

var GROUP byte = 0xa3
var CMD byte = 0x06

type CmdSendDynamicArea struct {
	baseBxCmd
	processMode byte
	r2          byte
	delAreaIds  []byte
	areas       []BxArea
}

func NewBxCmdSendDynamicArea(areas []BxArea) CmdSendDynamicArea {
	return CmdSendDynamicArea{
		baseBxCmd: newBaseCmd(CMD_SEND_DYNAMIC_AREA.group, CMD_SEND_DYNAMIC_AREA.code),
		areas:     areas,
	}
}

func (sd CmdSendDynamicArea) ProcessMode() byte {
	return sd.processMode
}

func (sd CmdSendDynamicArea) SetProcessMode(processMode byte) {
	sd.processMode = processMode
}

func (sd CmdSendDynamicArea) R2() byte {
	return sd.r2
}

func (sd CmdSendDynamicArea) SetR2(r2 byte) {
	sd.r2 = r2
}

func (sd CmdSendDynamicArea) DelAreaIds() []byte {
	return sd.delAreaIds
}

func (sd CmdSendDynamicArea) SetDelAreaIds(delAreaIds []byte) {
	sd.delAreaIds = delAreaIds
}

func (sd CmdSendDynamicArea) Areas() []BxArea {
	return sd.areas
}

func (sd CmdSendDynamicArea) SetAreas(areas []BxArea) {
	sd.areas = areas
}

func (sd CmdSendDynamicArea) Build() []byte {
	w := bytes.NewBuffer(make([]byte, 0, 1024))
	binary.Write(w, binary.LittleEndian, sd.Group())
	binary.Write(w, binary.LittleEndian, sd.Cmd())
	binary.Write(w, binary.LittleEndian, sd.ReqResp())
	binary.Write(w, binary.LittleEndian, sd.processMode)
	binary.Write(w, binary.LittleEndian, sd.r2)
	if sd.delAreaIds == nil {
		binary.Write(w, binary.LittleEndian, byte(0x00))
	} else {
		binary.Write(w, binary.LittleEndian, byte(len(sd.delAreaIds)))
		binary.Write(w, binary.LittleEndian, sd.delAreaIds)
	}
	if sd.areas == nil || len(sd.areas) == 0 {
		binary.Write(w, binary.LittleEndian, byte(0x00))
	} else {
		binary.Write(w, binary.LittleEndian, byte(len(sd.areas)))
		for _, v := range sd.areas {
			b := v.Build()
			binary.Write(w, binary.LittleEndian, int16(len(b)))
			binary.Write(w, binary.LittleEndian, b)
		}
	}
	return w.Bytes()
}
