using System.Collections.Generic;
using System.Linq;

namespace InABox.DigitalMatter
{
    public class DMAnalogueDataField16 : DMField
    {
        public DMAnalogueDataField16()
        {
            Data = new Dictionary<byte, short>();
        }

        public override byte Type => 0x06;

        public Dictionary<byte, short> Data { get; }

        public double InternalVoltage => Data.ContainsKey(1) ? (double)Data[1] / 100.0F : 0.0F;
        public double ExternalVoltage => Data.ContainsKey(2) ? (double)Data[2] / 100.0F : 0.0F;
        public double InternalTemperature => Data.ContainsKey(3) ? (double)Data[3] / 100.0F : 0.0F;
        public int GSMStrength => Data.ContainsKey(4) ? Data[4] : 0;
        public double LoadedVoltage => Data.ContainsKey(5) ? (double)Data[5] / 100.0F : 0.0F;
        public double? BatteryStrength => Data.ContainsKey(6) ? (double)Data[6] / 100.0F : new double?();

        protected override void DoDecode(IDMReadBuffer buffer)
        {
            for (var i = 0; i < Length; i += 3)
                Data[buffer.TakeByte()] = buffer.TakeInt16();
        }

        protected override void DoEncode(IDMWriteBuffer buffer)
        {
            foreach (var key in Data.Keys)
            {
                buffer.AddByte(key);
                buffer.AddInt16(Data[key]);
            }
        }

        public override string ToString()
        {
            return string.Join(" ", Data.Select(x => string.Format("{0:X}={1}", x.Key, x.Value)));
        }

        public override bool IsValid()
        {
            return Data.Any();
        }
    }
}