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()
        {
            base.BeforeDecode();
            var header = TakeByte();
            DataLength = EncodeByte(DecodeByte(header, 0, 6));
            LogReason = EncodeByte(DecodeByte(header, 6, 2));
            TagType = TakeByte();
            RSSI = TakeInt8();
        }

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

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

        protected override void DoEncode()
        {
            AddBytes(Tag.Encode());
        }

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

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