using System;

namespace BeWo.Core
{
    public static class AutoLockUI
    {
        private static System.Windows.Forms.Timer _Timer;

        public static int LockUITime { get; set; }

        public delegate void DoAutoLockUI();
        public static event DoAutoLockUI DoAutoLockUIEvent;

        static public void StartAutoLockUIOption()
        {
            System.Windows.Interop.ComponentDispatcher.ThreadIdle += DispatcherQueueEmptyHandler;
        }

        static void _timerTick(object sender, EventArgs e)
        {
            if (_Timer == null) return;

            System.Windows.Interop.ComponentDispatcher.ThreadIdle -= DispatcherQueueEmptyHandler;
            _Timer.Stop();
            _Timer = null;

            if (DoAutoLockUIEvent != null)
                DoAutoLockUIEvent();
        }

        public static void StopTimer()
        {
            if (_Timer == null) return;

            System.Windows.Interop.ComponentDispatcher.ThreadIdle -= DispatcherQueueEmptyHandler;
            _Timer.Stop();
            _Timer = null;
        }

        static void DispatcherQueueEmptyHandler(object sender, EventArgs e)
        {
            if (_Timer == null)
            {
	            if (LockUITime > 0)
	            {
		            _Timer = new System.Windows.Forms.Timer {Interval = LockUITime*60*1000};
		            _Timer.Tick += _timerTick;
		            _Timer.Enabled = true;
	            }
            }
            else if (_Timer.Enabled == false)
            {
	            _Timer.Enabled = true;
            }
            else
            {
	            if (LockUITime == 0)
					StopTimer();
            }
        }

        public static void ResetLockUITimer()
        {
            if (_Timer == null) return;

            _Timer.Enabled = false;
            _Timer.Enabled = true;
        }
    }
}
