using System;
using System.Threading;
using Microsoft.SPOT;

namespace CPF
{
    public class Ticker
    {
        public delegate void    Tick();
        public Tick             OnTick;
 
        private Thread          _thread;
        private TimerCallback   _timerCallback;
        private Timer           _timer;
        private AutoResetEvent  _timeout;

        private void Timeout(object unused)
        {
            _timeout.Set();
        }

        private void Run()
        {

            while (true)
            {
                _timeout.WaitOne();
                // if anyone has subscribed, notify them
                if (OnTick != null)
                    OnTick();
            }
        }

        public Ticker(double tickRateIn_Hz, int delayUntilStartIn_mSecs)
        {
            _timeout = new AutoResetEvent(false);
            _thread = new Thread(new ThreadStart(Run));
            _timerCallback = new TimerCallback(Timeout);
            int tickRateIn_mSec = Tools.SampleRateIn_mSec(tickRateIn_Hz);
            _timer = new Timer(_timerCallback, null, delayUntilStartIn_mSecs, tickRateIn_mSec);
        }

        public void Start()
        {
            _thread.Start();
        }

        public void Stop()
        {
            _timer.Dispose();
            _timer = null;
            _thread.Suspend();
        }
    }
}