package com.qmth.paper.library.common.lock;

import com.qmth.paper.library.common.lock.impl.CustomLockProvider;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component("lockService")
public class LockService implements InitializingBean, ApplicationContextAware {

    protected static final Logger log = LoggerFactory.getLogger(LockService.class);

    private static final String KEY_JOINER = "\t";

    private ApplicationContext context;

    private LockProvider provider;

    /**
     * 尝试获取排他锁，立即返回获取结果
     *
     * @param type
     * @param keys
     * @return
     */
    public boolean trylock(LockType type, Object... keys) {
        return provider.tryLock(type, getKeys(keys));
    }

    /**
     * 等待获取排他锁，线程阻塞直到成功获取
     *
     * @param type
     * @param keys
     */
    public void waitlock(LockType type, Object... keys) {
        provider.waitLock(type, getKeys(keys));
    }

    /**
     * 释放已获取的排他锁
     *
     * @param type
     * @param keys
     */
    public void unlock(LockType type, Object... keys) {
        provider.unlock(type, getKeys(keys));
    }

    /**
     * 检测排他锁是否已被获取
     *
     * @param type
     * @param keys
     * @return
     */
    public boolean isLocked(LockType type, Object... keys) {
        return provider.isLocked(type, getKeys(keys));
    }

    /**
     * 等待获取可重入的读锁
     *
     * @param type
     * @param keys
     */
    public void watch(LockType type, Object... keys) {
        provider.watch(type, getKeys(keys));
    }

    /**
     * 释放已获取的读锁
     *
     * @param type
     * @param keys
     */
    public void unwatch(LockType type, Object... keys) {
        provider.unwatch(type, getKeys(keys));
    }

    /**
     * 释放长时间未使用的锁
     */
    public void clear() {
        provider.clear();
    }

    private String getKeys(Object... keys) {
        return StringUtils.join(keys, KEY_JOINER);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.provider = this.context.getBean(CustomLockProvider.class);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }
}
