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

namespace Server.Core
{
    public class ThreadSynchronizationContext : SynchronizationContext
    {
        private readonly ConcurrentQueue<Action> queue = new ConcurrentQueue<Action>();

        private Action a;

        private int actorTypeId;
        
        public int MsgCount
        {
            get
            {
                return queue.Count;
            }
        }
        
        public ThreadSynchronizationContext()
        {
            
        }
        
        public ThreadSynchronizationContext(int actorTypeId = -1)
        {
            this.actorTypeId = actorTypeId;
        }

        public void Update()
        {
            int count = this.queue.Count;
            while (count -- > 0)
            {
                if (!this.queue.TryDequeue(out a))
                {
                    return;
                }

                try
                {
                    a();
                }
                catch (Exception e)
                {
                    Debug.Error($"Post: {e.Message} ");
                }
            }
        }

        public override void Post(SendOrPostCallback callBack, object state)
        {
            this.Post(()=>callBack(state));
        }

        public void Post(Action action)
        {
            //Debug.Info("添加Action!");
            this.queue.Enqueue(action);
        }
    }
}