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()
        {
            UUID = TakeBytes(16);
            MajorID = TakeUInt16();
            MinorID = TakeUInt16();
            TxPower = TakeInt8();
            if (DataLength == 27)
                MacAddress = TakeBytes(6);
        }

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

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

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