using CrazyStudio.Core.Common.Status;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrazyStudio.Core.Common.Game
{
    public class GameLogicServer : IDisposable
    {
        private readonly FPSCounter _fpsCounter = new FPSCounter();
        private readonly Stopwatch _stopwatch = new Stopwatch();
        private readonly int _targetFPS = 90;
        private readonly long _targetIntervalTicks;
        //private long _nextFrameTime;
        //private readonly SpinWait _spinWait = new SpinWait();
        private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
        private bool _isRunning;

        public bool IsRunning { get => _isRunning; }
        //set => _isRunning = value; }
        //private SpinWait spinner = new SpinWait();

        public GameLogicServer()
        {
            _targetIntervalTicks = Stopwatch.Frequency / _targetFPS;
        }

        public void Start()
        {
            if (IsRunning) return;

            _isRunning = true;
            Task.Run(() => RunFrameLoop(_cancellationTokenSource.Token));
            //Console.WriteLine($"Game logic server started");
        }

        public void Stop()
        {
            if (!IsRunning) return;

            _stopwatch.Stop();

            _cancellationTokenSource.Cancel();
            _isRunning = false;
            //Console.WriteLine("Game logic server stopped");
        }

        private DateTime _lastPerformanceCheck = DateTime.UtcNow;

        private void MonitorPerformance()
        {
            // 开始帧计时
            _fpsCounter.Update();
            if (DateTime.UtcNow - _lastPerformanceCheck > TimeSpan.FromSeconds(1))
            {
                _lastPerformanceCheck = DateTime.UtcNow;
                //var cpuUsage = Process.GetCurrentProcess().TotalProcessorTime;
                //var memoryUsage = GC.GetTotalMemory(false);
                Console.WriteLine($"FPS: {_fpsCounter.CurrentFPS}");//, CPU: {cpuUsage}, Memory: {memoryUsage} bytes");
            }
        }

        private void RunFrameLoop(CancellationToken cancellationToken)
        {
            _stopwatch.Start();
            _lastPerformanceCheck = DateTime.UtcNow;
            //_nextFrameTime = _stopwatch.ElapsedTicks;
            while (!cancellationToken.IsCancellationRequested)
            {
                long frameStart = _stopwatch.ElapsedTicks;

                //// 1. 处理玩家输入（示例）
                //ProcessPlayerInputs();

                //// 2. 更新游戏逻辑（示例）
                //UpdateGameState();

                // 3. 同步状态到客户端（示例）
                SyncGameStateToClients();

                //MonitorPerformance();

                // 计算剩余时间
                long elapsedTicks = _stopwatch.ElapsedTicks - frameStart;
                long sleepTime = _targetIntervalTicks - elapsedTicks;


                if (sleepTime > 0)
                {
                    //this.sleepTime = sleepTime;
                    SpinWait.SpinUntil(() => false, TimeSpan.FromTicks(sleepTime)); // 自旋等待
                }

                // 动态校准时间
                //_nextFrameTime = _stopwatch.ElapsedTicks + _targetIntervalTicks;
            }
        }

        private void ProcessPlayerInputs()
        {
            //// 实现输入处理逻辑（如网络消息解析）
            //// 示例：模拟处理100个玩家输入
            //Parallel.For(0, 100, i =>
            //{
            //    // 处理第i个玩家的输入
            //});
            ProcessPlayerInputsEvents?.Invoke();
        }

        private void UpdateGameState()
        {
            // 实现游戏状态更新逻辑（物理、AI等）
            // 示例：分帧处理不同模块
            Parallel.Invoke(
                () => UpdatePhysics?.Invoke(),
                () => UpdateAI?.Invoke(),
                () => HandleCombat?.Invoke()
            );
        }

        private void SyncGameStateToClients()
        {
            // 实现状态同步逻辑（网络广播）
            // 示例：批量发送状态更新
            SyncGameStateToClientsEvents?.Invoke();
        }

        //private void SpinWaitUntil(long targetTicks, CancellationToken token)
        //{
        //    long remainingTicks = targetTicks;
        //    while (remainingTicks > 0 && !token.IsCancellationRequested)
        //    {
        //        // 动态调整自旋策略
        //        if (_stopwatch.ElapsedTicks - _stopwatch.ElapsedTicks >= targetTicks)
        //            break;

        //        _spinWait.SpinOnce();

        //        //// 检查取消请求
        //        //token.ThrowIfCancellationRequested();
        //    }
        //}

        public void Dispose()
        {
            Stop();
            _cancellationTokenSource.Dispose();
            _stopwatch.Stop();
        }

        // 示例子系统方法
        public event Action? UpdatePhysics = null;
        public event Action? UpdateAI = null;
        public event Action? HandleCombat = null;
        public event Action? ProcessPlayerInputsEvents = null;
        public event Action? SyncGameStateToClientsEvents = null;

        public void SetSyncGameStateToClientsEvents(Action syncGameStateToClientsEvents)
        {
            SyncGameStateToClientsEvents = syncGameStateToClientsEvents;
        }
    }
}
