using Hotline.Caches;
using Hotline.CallCenter.Calls;
using XF.Domain.Cache;
using XF.Domain.Dependency;

namespace Hotline.CacheManager
{
    public class CallCacheManager : ICallCacheManager, IScopeDependency
    {
        private readonly ITypedCache<List<Call>> _cacheCall;
        private const string CallKey = "CallQueue";

        public CallCacheManager(ITypedCache<List<Call>> cacheCall)
        {
            _cacheCall = cacheCall;
        }

        /// <summary>
        /// 新增或修改队列
        /// </summary>
        /// <param name="list"></param>
        public void AddCallCache(Call call)
        {
            var list = GetCallQueueList();
            if (list == null)
            {
                list = new List<Call>();
            }
            list.Add(call);
            _cacheCall.AddOrUpdate(CallKey, list);
        }

        /// <summary>
        /// 获取队列
        /// </summary>
        /// <returns></returns>
        public List<Call>? GetCallQueueList()
        {
            var list = _cacheCall.GetOrAdd(CallKey, k =>
            {
                return new List<Call>();
            });
            return list;
        }


        /// <summary>
        /// 删除队列
        /// </summary>
        /// <param name="id"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void RemoveCallCache(string id)
        {
            var list = _cacheCall.Get(CallKey)?.ToList();
            if (list != null)
            {
                var model = list.FirstOrDefault(x => x.Id == id);
                if (model != null)
                {
                    list.Remove(model);
                    _cacheCall.AddOrUpdate(CallKey, list);
                }
            }
        }
    }
}
