using System.Collections.Concurrent;
using MrWu.Debug;
using System.Threading;
using Server.Core;

namespace Server
{
    public class UUIDManager : SingleInstance<UUIDManager>
    {
        private Thread _thread;

        private readonly ConcurrentQueue<string> uuids = new ConcurrentQueue<string>();

        private bool isClose;
        
        /// <summary>
        /// 最大预生产 数
        /// </summary>
        public const int MaxCnt = 30;
        
        public UUIDManager()
        {
            _thread = new Thread(Run);
            _thread.IsBackground = true;
            _thread.Start();
        }

        private void Run()
        {
            #if DEBUG
            uint threadId = ThreadHelper.GetOSThreadId();
            Debug.Info($"ThreadStart UUIDManager {threadId}");
            #endif
            
            while (true)
            {
                if (isClose)
                {
                    break;
                }
                
                Thread.Sleep(10);
                if (uuids.Count >= MaxCnt)
                {
                    continue;
                }
                uuids.Enqueue(System.Guid.NewGuid().ToString().Replace("-",""));
            }
        }

        public string Get()
        {
            if (uuids.TryDequeue(out string uuid))
            {
                return uuid;
            }

            return System.Guid.NewGuid().ToString().Replace("-", "");
        }

        public void Close()
        {
            isClose = true;
        }
    }
}