package com.itheima.redission;

import jodd.time.TimeUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/*****
 * @Author: http://www.itheima.com
 * @Description: com.itheima.redission.RedissonDistributedLocker
 ****/
@Component
public class RedissonDistributedLocker implements DistributedLocker {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public RLock lock(String lockkey) {
        RLock lock = redissonClient.getLock(lockkey);
        lock.lock();
        return lock;
    }

    @Override
    public RLock lock(String lockkey, Long lesstime) {
        RLock lock = redissonClient.getLock(lockkey);
        lock.lock(lesstime, TimeUnit.SECONDS);
        return lock;
    }

    @Override
    public RLock lock(String lockkey, Long lesstime, TimeUnit timeUtil) {
        RLock lock = redissonClient.getLock(lockkey);
        lock.lock(lesstime, timeUtil);
        return lock;
    }

    @Override
    public Boolean lock(String lockkey, Long lesstime, TimeUnit timeUtil, Long timeout) {
        try {
            RLock lock = redissonClient.getLock(lockkey);
            return lock.tryLock(timeout,lesstime,timeUtil);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void unlock(String key) {
        RLock lock = redissonClient.getLock(key);
        lock.unlock();
    }

    @Override
    public void unlock(RLock rLock) {
        rLock.unlock();
    }
}
