using System;
using System.IO;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.IO;
using GHI.Premium.IO;

namespace CPF
{
    public class Controller
    {
        private HSM                         _aHSM;
        private Thread                      _HSM_Thread;
        private SynchronizedEventQueue      _anEventQ;
        private Ticker                      _aTicker;
        private PressureSensor              _aDGH;
        private int                         _ticksSinceReboot;

        public Controller(HSM thisHSM)
        {
            _HSM_Thread = new Thread(new ThreadStart(Run));
            _anEventQ = new SynchronizedEventQueue(128);
            _aHSM = thisHSM;
            _aTicker = new Ticker(1, 1000);
            _aDGH = new PressureSensor("com3", 38400, 10, 1000);
            _ticksSinceReboot = 0;
            _aTicker.OnTick += new Ticker.Tick(Tick);
            _aDGH.OnPressureChange += new PressureSensor.Pressure(ReportPressure);
            AutoResetEvent Arrived = new AutoResetEvent(false);
        }

        public void Start()
        {
            _aTicker.Start();
            _aDGH.Start();
            _HSM_Thread.Start();
        }

        // Stops listening to the Pressure Sensor
        public void Stop()
        {
            _aTicker.Stop();
            _aDGH.Stop();
            _HSM_Thread.Suspend();
        }

        public void Add(Signal s)
        {
            _anEventQ.Add(s, 0.0, 0);
        }

        public void Add(Signal s, double dval)
        {
            _anEventQ.Add(s, dval, 0);
        }

        public void Add(Signal s, int ival)
        {
            _anEventQ.Add(s, 0.0, ival);
        }

        // the method that implements the
        // delegated functionality
        private void Tick()
        {
            Add((Signal)ProfilerEvents.ReportTick, _ticksSinceReboot);
            _ticksSinceReboot++;
        }

        private void ReportPressure(double decibars)
        {
            Add((Signal)ProfilerEvents.ReportPressure, decibars);
        }

        private void Run()
        {
            while (true)
            {
                Event anEvent = _anEventQ.Remove();
                _aHSM.SignalCurrentState(anEvent);
            }
        }
    }
}
