using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Quadarax.Foundation.Core.Logging;

namespace qdr.fnd.core.pqueue.Storages
{
    public class MemoryStorageProvider : BaseStorageProvider
    {

        private ConcurrentDictionary<string, IPsQueueItem> _items = new ConcurrentDictionary<string, IPsQueueItem>();

        /// <inheritdoc />
        public MemoryStorageProvider(ILogger? logger) : base(logger)
        {
        }

        #region Overrides of BaseStorageProvider

        #endregion

        #region Overrides of DisposableObject

        /// <inheritdoc />
        protected override void OnDisposing()
        {
            _items.Clear();
            _items = null!;
        }

        #endregion

        #region Overrides of BaseStorageProvider

        /// <inheritdoc />
        protected override string OnCreateItem(string id, string owner, string ownerRef, string providerClass, int initialAttempts,
            DateTime created, string s)
        {
            var item = new PsQueueItem(id, owner, ownerRef, providerClass, created)
            {
                AttemptsLeft = initialAttempts
            };
            if(!_items.TryAdd(id, item))
                Log?.Log(LogSeverityEnum.Warn, $"Item id={id} already exists in storage (id conflict)");
            return id;
        }

        /// <inheritdoc />
        protected override void OnDeleteItem(string itemId)
        {
            if(_items.TryRemove(itemId, out _))
                Log?.Log(LogSeverityEnum.Warn, $"Item id={itemId} wasn't delete from storage (not exists)");
        }

        /// <inheritdoc />
        public override bool ContainsItem(string itemId)
        {
            return _items.ContainsKey(itemId);
        }

        #endregion
    }
}
