using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EasyCaching.Core;
using XF.Domain.Dependency;
using XF.Domain.Locks;

namespace XF.EasyCaching
{
    public class DefaultDistributedLock : IDistributedLock, IScopeDependency
    {
        private readonly IRedisCachingProvider _redisCaching;

        public DefaultDistributedLock(IRedisCachingProvider redisCaching)
        {
            _redisCaching = redisCaching;
        }

        public bool Acquire(string key, TimeSpan expired) => 
            _redisCaching.StringSet(key, key, expired, "nx");

        public async Task<bool> AcquireAsync(string key, TimeSpan expired, CancellationToken cancellationToken) => 
            await _redisCaching.StringSetAsync(key, key, expired, "nx");

        public void Release(string key) => _redisCaching.KeyDel(key);

        public async Task ReleaseAsync(string key, CancellationToken cancellationToken) => await _redisCaching.KeyDelAsync(key);
    }
}
