using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TwoMbit
{
    public class Events
    {
        ManualResetEvent raiseEvent;
        ManualResetEvent fetchEvent;

        public enum Job { UNLOAD, LOAD, POWER, RESET, EXIT, SETTINGS, NOTHING };

        Dictionary<int, bool> jobs;

        public Events()
        {
            jobs = new Dictionary<int, bool>();
            jobs[(int)Job.UNLOAD] = false;
            jobs[(int)Job.LOAD] = false;
            jobs[(int)Job.POWER] = false;
            jobs[(int)Job.RESET] = false;
            jobs[(int)Job.EXIT] = false;
            jobs[(int)Job.SETTINGS] = false;

            raiseEvent = new ManualResetEvent(true);
            fetchEvent = new ManualResetEvent(true);
        }

        public void raise(Job job)
        {
            fetchEvent.WaitOne();
            raiseEvent.Reset();
            jobs[(int)job] = true;
            raiseEvent.Set();
        }

        public Job checkForUnfinishedJobs()
        {
            raiseEvent.WaitOne();
            fetchEvent.Reset();
            foreach (KeyValuePair<int, bool> _event in jobs) {
                if (isPending((Job)_event.Key)) {
                    fetched((Job)_event.Key);
                    Job todo = (Job)_event.Key;
                    fetchEvent.Set();
                    return todo;
                }
            }
            fetchEvent.Set();
            return Job.NOTHING;
        }

        void fetched(Job job)
        {
            jobs[(int)job] = false;
        }

        bool isPending(Job job)
        {
            return jobs[(int)job];
        }
    }
}
