namespace InABox.DigitalMatter
{
    public class DMBluetoothTagListItem : DMObject
    {
        public byte DataLength { get; set; }

        public byte LogReason { get; set; }

        public byte TagType { get; set; }

        public sbyte RSSI { get; set; }

        public DMBluetoothTag Tag { get; set; }

        protected override void BeforeDecode(IDMReadBuffer buffer)
        {
            base.BeforeDecode(buffer);
            var header = buffer.TakeByte();
            DataLength = IDMBuffer.EncodeByte(IDMBuffer.DecodeByte(header, 0, 6));
            LogReason = IDMBuffer.EncodeByte(IDMBuffer.DecodeByte(header, 6, 2));
            TagType = buffer.TakeByte();
            RSSI = buffer.TakeInt8();
        }

        protected override void DoDecode(IDMReadBuffer buffer)
        {
            var data = buffer.TakeBytes(DataLength);
            Tag = DMFactory.ParseBluetoothTag(TagType, data);
        }

        protected override void BeforeEncode(IDMWriteBuffer buffer)
        {
            base.BeforeEncode(buffer);
            buffer.AddByte(TagType);
            buffer.AddInt8(RSSI);
        }

        protected override void DoEncode(IDMWriteBuffer buffer)
        {
            buffer.AddBytes(Tag.EncodeArray());
        }

        protected override void AfterEncode(IDMWriteBuffer buffer)
        {
            base.AfterEncode(buffer);
            var header = IDMBuffer.EncodeByte(IDMBuffer.DecodeByte(DataLength, 0, 6));
            header = IDMBuffer.UpdateByte(header, 6, IDMBuffer.DecodeByte(LogReason, 0, 2));
            buffer.InsertByte(0, header);
        }

        public override string ToString()
        {
            return string.Format("{0}{1}", LogReason == 1 ? "+" : LogReason == 2 ? "-" : "", Tag);
        }
    }
}