using System.Collections.Generic;

namespace InABox.DigitalMatter
{
    public enum GPSStatus
    {
        Valid,
        ThreeDimensional,
        NoSignal
    }

    public class DMGPSField : DMField
    {
        public override byte Type => 0x00;

        public uint TimeStamp { get; set; }
        public int Latitude { get; set; }
        public int Longitude { get; set; }
        public short Altitude { get; set; }
        public ushort Speed { get; set; }
        public byte SpeedAccuracy { get; set; }
        public byte Heading { get; set; }
        public byte PDOP { get; set; }
        public byte GPSAccuracy { get; set; }
        public byte Status { get; set; }

        public GPSStatus[] StatusFlags()
        {
            var result = new List<GPSStatus>();
            var flags = DecodeByte(Status, 1, 8);
            if (flags[0])
                result.Add(GPSStatus.Valid);
            if (flags[1])
                result.Add(GPSStatus.ThreeDimensional);
            if (flags[2])
                result.Add(GPSStatus.NoSignal);
            return result.ToArray();
        }

        public override bool IsValid()
        {
            return Status != 0;
        }


        public override string ToString()
        {
            return string.Format("{0:dd MMM yy hh-mm-ss} Lat: {1:F6} Lng: {2:F6} Status: {3}", TimeStampToDateTime(TimeStamp),
                (double)Latitude / 10000000.0F, (double)Longitude / 10000000.0F, string.Join(",", StatusFlags()));
        }

        protected override void DoDecode()
        {
            TimeStamp = TakeUInt32();
            Latitude = TakeInt32();
            Longitude = TakeInt32();
            Altitude = TakeInt16();
            Speed = TakeByte();
            SpeedAccuracy = TakeByte();
            Heading = TakeByte();
            PDOP = TakeByte();
            GPSAccuracy = TakeByte();
            Status = TakeByte();
        }

        protected override void DoEncode()
        {
            AddUInt32(TimeStamp);
            AddInt32(Latitude);
            AddInt32(Longitude);
            AddInt16(Altitude);
            AddUInt16(Speed);
            AddByte(SpeedAccuracy);
            AddByte(Heading);
            AddByte(PDOP);
            AddByte(GPSAccuracy);
            AddByte(Status);
        }
    }
}