using System;
using System.Threading;
using System.IO.Ports;
using System.Text;

using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;

namespace CPF
{

    public class Bellows
    {
        // Called when the desired position has been reached
        public delegate void        Position(double mm);
        public Position             AtDesiredPosition;

        private enum                Location { Unknown, InTransit, AtDesired, UndershotDesired, OvershotDesired, BeyondLimits };

        private Thread              _bellowsThread;
        private TimerCallback       _timerCallback;
        private Timer               _timer;
        private AutoResetEvent      _sample;
        private PositionSensor      _aPositionSensor;
        private double              _sampleRateIn_Hz;

        private double              _desiredPosition_MM;
        private double              _deltaPosition_MM;
        private double              _lowerRetractionLimit;
        private double              _upperRetractionLimit;
        private double              _lowerExtensionLimit;
        private double              _upperExtensionLimit;
        private double              _lowerPositionLimit;
        private double              _upperPositionLimit;

        private int                 _delayUntilStartIn_mSecs;
        private int                 _movement;  // -1 = Retract. 1 = Extend, 0 = No Movement

        public Bellows(double sampleRateIn_Hz, int delayUntilStartIn_mSecs, double retractLimit = 20.0, double extendLimit = 100.0)
        {
            _aPositionSensor = new PositionSensor();
            _bellowsThread = new Thread(new ThreadStart(Run));
            _sampleRateIn_Hz = sampleRateIn_Hz;
            _delayUntilStartIn_mSecs = delayUntilStartIn_mSecs;
            _lowerRetractionLimit = retractLimit - 0.1;
            _upperRetractionLimit = retractLimit + 1.0;
            _lowerExtensionLimit = extendLimit - 1.0;
            _upperExtensionLimit = extendLimit + 0.1;
            _movement = 0;
        }

        // Starts listening to the Pressure Sensor
        private void Start()
        {
            _sample = new AutoResetEvent(false);
            _timerCallback = new TimerCallback(Sample);
            int sampleRateIn_mSec = Tools.SampleRateIn_mSec(_sampleRateIn_Hz);
            _timer = new Timer(_timerCallback, null, _delayUntilStartIn_mSecs, sampleRateIn_mSec);
            _bellowsThread.Start();
        }

        // Stops listening to the Pressure Sensor
        private void Stop()
        {
            _timer.Dispose();
            _timer = null;
            _bellowsThread.Suspend();
        }

        public double MaximumExtensionIn_MM { get; set; }

        public double MiminmumRetractionIn_MM { get; set; }

        public void MoveToPosition(double desired, double lowerPositionLimit, double upperPositionLimit, double velocity)
        {
            _desiredPosition_MM = desired;
            _lowerPositionLimit = lowerPositionLimit;
            _upperPositionLimit = upperPositionLimit;
            _deltaPosition_MM = _desiredPosition_MM - _aPositionSensor.Position;
            _movement = System.Math.Sign(_deltaPosition_MM);
            switch (_movement)
            {
                case 1:
                    // Elmo.Extend(velocity);
                    Start();
                    break;

                case 0: // Already there...
                    // Elmo.Stop();
                    break;

                case -1:
                    // Elmo.Retract(velocity);
                    Start();
                    break;

                default: // Can't happen... TO DO: deal with this ugliness
                    break;
            }
        }

        private void Sample(object unused)
        {
            _sample.Set();
        }

        public void Run()
        {
            double currentPositionIn_MM;
            while (true)
            {
                _sample.WaitOne();
                currentPositionIn_MM= _aPositionSensor.Position;
                switch (Where(currentPositionIn_MM))
                {
                    case Location.BeyondLimits :
                        break;

                    case Location.AtDesired :
                        AtDesiredPosition(_desiredPosition_MM);
                        Stop();
                        break;

                    case Location.InTransit :
                        break;

                    case Location.OvershotDesired :
                        break;

                    case Location.UndershotDesired:
                        break;

                    case Location.Unknown:
                        break;

                    default :
                        break;
                } 
            }
        }

        private Location Where(double positionIn_MM)
        {
            Location _location;
            if ((positionIn_MM < _lowerRetractionLimit) && (positionIn_MM > _upperRetractionLimit))
                _location = Location.BeyondLimits;
            else if ((positionIn_MM > _lowerPositionLimit) && (positionIn_MM < _upperPositionLimit))
                _location = Location.AtDesired;
            else if ((_movement > 0) && (positionIn_MM > _upperPositionLimit))
                _location = Location.OvershotDesired;
            else if ((_movement < 0) && (positionIn_MM < _lowerPositionLimit))
                _location = Location.UndershotDesired;
            else
                _location = Location.InTransit;

            return _location;
        }
    }
}

