using System;
using Optional;

namespace BoFilTest.Domain.Modules
{
    class VoegtlinGasFlowMeasure : IGasFlowMeasure
    {
        private static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private readonly VoegtlinDevice device;

        public VoegtlinGasFlowMeasure(VoegtlinDevice device)
        {
            this.device = device;
        }

        public int CalibrationCurveIndex
        {
            get
            {
                switch (device.ReadLUTIndex())
                {
                    default:
                    case VoegtlinDevice.FIRST_CURVE_HW_INDEX:
                        return 0;
                    case VoegtlinDevice.SECOND_CURVE_HW_INDEX:
                        return 1;
                }

            }
            set
            {
                switch (value)
                {
                    default:
                    case 0:
                        device.WriteLUTIndex(VoegtlinDevice.FIRST_CURVE_HW_INDEX);
                        return;
                    case 1:
                        device.WriteLUTIndex(VoegtlinDevice.SECOND_CURVE_HW_INDEX);
                        return;
                }
            }
        }

        public void Cleanup()
        {
        }

        public float? ReadIntegral()
        {
            try
            {
                return device.ReadTotalisator();
            }
            catch (Exception e)
            {
                logger.Error(e, "Unable to read voegtlin flow integral");
                return null;
            }
        }

        public Option<LiterPerHour> ReadValue()
        {
            try
            {
                return Option.Some(new LiterPerHour(device.ReadFlow()));
            }
            catch (Exception e)
            {
                logger.Error(e, "Unable to read voegtling flow value");
                return Option.None<LiterPerHour>();
            }
        }

        public void ResetIntegral()
        {
            try
            {
                device.WriteTotalisator(0.0f);
            }
            catch (Exception e)
            {
                logger.Error(e, "Unable to reset voegtlin flow integral");
            }
        }
    }
}
