using BoFilTest.Utils;
using Optional;
using System;

namespace BoFilTest.Domain.Modules
{
    class EmulatedGasFlowMeasure : IGasFlowMeasure
    {
        private readonly SecondTimer timer;
        private float integral;
        private double lastTime;
        private double lastValue;

        public EmulatedGasFlowMeasure()
        {
            timer = new SecondTimer();
            integral = 0.0f;
        }

        public int CalibrationCurveIndex { get; set; }

        public void Cleanup()
        {
            // Nothing to do
        }

        public float? ReadIntegral()
        {
            return integral;
        }

        public Option<LiterPerHour> ReadValue()
        {
            var time = timer.Get();
            double value = Math.IEEERemainder(time, 15.0);
            var result = Option.Some(new LiterPerHour(value));

            // Sum up into integral
            integral += (float)((time - lastTime) * (Math.Abs(lastValue) + Math.Abs(value)) * 0.5);
            lastValue = value;
            lastTime = time;

            return result;
        }

        public void ResetIntegral()
        {
            integral = 0.0f;
        }
    }
}
