using System;
using System.Threading;

namespace OmniBeanEB.Library
{
	[SmallBasicType]
	public class Timer
	{
		public const int _maxInterval = 100000000;

		private static int _interval;

		private static System.Threading.Timer _threadTimer;

		private static event SmallBasicCallback _tick;

		public static event SmallBasicCallback Tick
		{
			add
			{
				Timer._tick = null;
				Timer._tick += value;
			}
			remove
			{
				Timer._tick -= value;
			}
		}

		public static EBPrimitive Interval
		{
			get
			{
				return Timer._interval;
			}
			set
			{
				Timer._interval = value;
				Timer._interval = Math.Max(10, Math.Min(Timer._interval, 100000000));
				Timer._threadTimer.Change(Timer._interval, Timer._interval);
			}
		}

		static Timer()
		{
			Timer._interval = 100000000;
			Timer._threadTimer = new System.Threading.Timer(new TimerCallback(Timer.ThreadTimerCallback));
		}

		public static void Pause()
		{
			Timer._threadTimer.Change(-1, -1);
		}

		public static void Resume()
		{
			Timer._threadTimer.Change(Timer._interval, Timer._interval);
		}

		private static void ThreadTimerCallback(object tag)
		{
			if (Timer._tick != null)
			{
				Timer._tick();
			}
		}
	}
}
