using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Assets.Scripts.Devices.Ant.Pages
{
    public class PowerOnlyPageHandler : IPageHandler
    {
        private DateTime _lastEventChange = DateTime.UtcNow;
        private byte _previousEventCount;

        public bool CanHandle(byte pageNumber)
        {
            return (int)pageNumber == 16;
        }

        public void Handle(byte[] dataPayload, AbstractAntDevice device)
        {
            var powerDevice = device as PowerDevice;
            if (powerDevice == null)
            {
                return;
            }

            //var dataPayload = response.messageContents.Skip(1).ToArray();
            byte currentVal = dataPayload[1];
            if ((int)ByteExtensions.GetDifference(currentVal, this._previousEventCount) > 0) //ByteExtensions
                this._lastEventChange = DateTime.UtcNow;
            this._previousEventCount = currentVal;
            powerDevice.Power = this.IsNotMovingDueToNoEventChanges() ? 0 : (ushort)((uint)dataPayload[6] | (uint)dataPayload[7] << 8);
            if ((int)dataPayload[3] != (int)byte.MaxValue)
                powerDevice.Cadence = (this.IsNotMovingDueToNoEventChanges() ? 0 : (int)dataPayload[3]);
            else
                powerDevice.Cadence = 0;
            //int num1 = (int)dataPayload[2];
            //int num2 = 128;
            //bool flag = (uint)(num1 & num2) > 0U;
            //int num3 = (int)sbyte.MaxValue;
            //int num4 = num1 & num3;
            //int num5 = (int)byte.MaxValue;
        }

        private bool IsNotMovingDueToNoEventChanges()
        {
            return this._lastEventChange.AddSeconds(3.0) <= DateTime.UtcNow;
        }
    }
}
