package cn.wise.sc.cement.business.config.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Function;

@Slf4j
public class RedissonDistributedLocker implements DistributedLocker {

	private RedissonClient redissonClient;

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

	@Override
	public RLock lock(String lockKey, int leaseTime) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock(leaseTime, TimeUnit.SECONDS);
		return lock;
	}

	@Override
	public RLock lock(String lockKey, TimeUnit unit, int timeout) {
		RLock lock = redissonClient.getLock(lockKey);
		lock.lock(timeout, unit);
		return lock;
	}

	@Override
	public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
		RLock lock = redissonClient.getLock(lockKey);
		try {
			return lock.tryLock(waitTime, leaseTime, unit);
		} catch (InterruptedException e) {
			return false;
		}
	}

	public static void realeaseLock(RLock fairLock) {
		fairLock.unlock();
	}

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

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

	@Override
	public <T> T executeLock(String key, Function<String, T> function, String t) {
		RLock lock = redissonClient.getLock(key);
		boolean locked = false;
		try {
			lock.lock();

			return (T) function.apply(t);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return null;
	}

	@Override
	public <T> void executeLock(String lockKey, Consumer<T> consumer, T t) {
		RLock lock = redissonClient.getLock(lockKey);
		boolean locked = false;
		try {
			while (true) {
				locked = lock.tryLock();
				if (locked) break;
			}
			if (locked) {
				consumer.accept(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (locked) {
				lock.unlock();
			}
		}
	}

	public void setRedissonClient(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}

}