namespace InABox.DigitalMatter
{
    public class DMBluetoothTagData : DMField
    {
        public override byte Type => 0x1E;

        public byte DataLength { get; set; }
        public byte LogReason { get; set; }
        public byte TagType { get; set; }
        public sbyte RSSI { get; set; }
        public uint TimeStamp { get; set; }
        public int Latitude { get; set; }
        public int Longitude { get; set; }
        public byte GPSAccuracy { get; set; }

        public DMBluetoothTag Tag { get; set; }

        public override bool IsValid()
        {
            return true;
        }

        protected override void DoDecode()
        {
            var header = TakeByte();
            DataLength = EncodeByte(DecodeByte(header, 0, 6));
            LogReason = EncodeByte(DecodeByte(header, 6, 2));
            TagType = TakeByte();
            RSSI = TakeInt8();
            TimeStamp = TakeUInt32();
            Latitude = TakeInt32();
            Longitude = TakeInt32();
            GPSAccuracy = TakeByte();
            var data = TakeBytes(DataLength);
            Tag = DMFactory.ParseBluetoothTag(TagType, data);
        }

        protected override void DoEncode()
        {
            AddByte(TagType);
            AddInt8(RSSI);
            AddUInt32(TimeStamp);
            AddInt32(Latitude);
            AddInt32(Longitude);
            AddByte(GPSAccuracy);

            var data = Tag.Encode();
            AddBytes(data);

            DataLength = (byte)data.Length;
            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} {2:dd MMM yy hh-mm-ss} Lat: {3:F6} Lng: {4:F6} RSSI: {5}", Tag,
                LogReason == 1 ? "Found" : LogReason == 2 ? "Lost" : "Updated", TimeStampToDateTime(TimeStamp), (double)Latitude / 10000000.0F,
                (double)Longitude / 10000000.0F, RSSI);
        }
    }
}