using Permission;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace YangjieTester
{
    public class InputMessageFilter : IMessageFilter
    {
        public bool PreFilterMessage(ref Message m)
        {
            const int LBUTTONDOWN = 0x0201;
            const int LBUTTONUP = 0x0202;
            const int KEYDOWN = 0x0100;

            if (m.Msg == LBUTTONDOWN || m.Msg == LBUTTONUP || m.Msg == KEYDOWN)
            {
                InactivityMonitor.RecordActivity();
            }

            return false; // 不拦截消息，继续传递
        }
    }
    public static class InactivityMonitor
    {
        private static DateTime _lastActivity = DateTime.Now;
        private static System.Threading.Timer _timer;
        private static readonly object _lock = new object();

        static InactivityMonitor()
        {
            _timer = new System.Threading.Timer(CheckInactivity, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
        }

        public static void RecordActivity()
        {
            lock (_lock)
            {
                _lastActivity = DateTime.Now;
            }
        }

        private static void CheckInactivity(object state)
        {
            TimeSpan idle;
            lock (_lock)
            {
                idle = DateTime.Now - _lastActivity;
            }

            if (idle >= TimeSpan.FromMinutes(10))
            {
                // 回到 UI 线程执行操作
                if (Application.OpenForms.Count > 0)
                {
                    var mainForm = Application.OpenForms[0];
                    if (!mainForm.IsDisposed)
                    {
                        mainForm.BeginInvoke(new Action(() =>
                        {
                            PerformAutoAction();
                        }));
                    }
                }
            }
        }

        private static void PerformAutoAction()
        {
            // 比如退出、锁屏等
            // Application.Exit(); 
            PermissionManager.LogOffAndSignInOperator();
        }
    }
}
