using System.Collections.Generic;
using System.Threading.Tasks;
using MrWu.Debug;

namespace Server.Core
{
    public class CoroutineLockQueueType
    {
        public int Type
        {
            get;
            private set;
        }

        public CoroutineLockManager CoroutineLockManager
        {
            get;
            private set;
        }

        private Dictionary<long, CoroutineLockQueue> CoroutineLockQueues = new Dictionary<long, CoroutineLockQueue>();

        public CoroutineLockQueueType(int type,CoroutineLockManager coroutineLockManager)
        {
            this.Type = type;
            this.CoroutineLockManager = coroutineLockManager;
        }

        private CoroutineLockQueue GetOrAdd(long key)
        {
            if (!this.CoroutineLockQueues.TryGetValue(key,out CoroutineLockQueue queue))
            {
                queue = CoroutineLockQueue.Create(this.Type, key,this.CoroutineLockManager);
                this.CoroutineLockQueues.Add(key,queue);
            }

            return queue;
        }

        private CoroutineLockQueue Get(long key)
        {
            if (!this.CoroutineLockQueues.TryGetValue(key,out CoroutineLockQueue queue))
            {
                queue = null;
            }
            return queue;
        }

        private void Remove(long key)
        {
            this.CoroutineLockQueues.Remove(key);
        }

        public async Task<CoroutineLock> Wait(long key,int time)
        {
            CoroutineLockQueue queue = GetOrAdd(key);
            Debug.Log($"CoroutineLockQueueType Wait {key}");
            return await queue.Wait(time);
        }

        public void Notify(long key,int level)
        {
            CoroutineLockQueue queue = Get(key);
            if (queue == null)
            {
                return;
            }

            if (!queue.Notify(level))
            {
                queue.Dispose();
                Remove(key);
            }
        }
    }
}