using System.Linq;

namespace InABox.DigitalMatter
{
    public class DMIBeaconBluetoothTag : DMBluetoothTag
    {
        public byte[] UUID { get; set; }

        public ushort MajorID { get; set; }

        public ushort MinorID { get; set; }

        public sbyte TxPower { get; set; }

        public byte[] MacAddress { get; set; }

        public override string ID()
        {
            return MacAddress != null
                ? string.Join(":", MacAddress.Reverse().Select(x => x.ToString("X2")))
                : string.Format("{0}.{1}", MajorID, MinorID);
        }

        protected override void DoDecode(IDMReadBuffer buffer)
        {
            UUID = buffer.TakeBytes(16);
            MajorID = buffer.TakeUInt16();
            MinorID = buffer.TakeUInt16();
            TxPower = buffer.TakeInt8();
            if (DataLength == 27)
                MacAddress = buffer.TakeBytes(6);
        }

        protected override void BeforeEncode(IDMWriteBuffer buffer)
        {
            base.BeforeEncode(buffer);
            DataLength = (byte)(MacAddress == null ? 21 : 27);
        }

        protected override void DoEncode(IDMWriteBuffer buffer)
        {
            buffer.AddBytes(UUID);
            buffer.AddUInt16(MajorID);
            buffer.AddUInt16(MinorID);
            buffer.AddInt8(TxPower);
            if (MacAddress != null)
                buffer.AddBytes(MacAddress);
        }

        public override string Type()
        {
            return "iBeacon";
        }
    }
}