package cn.com.qmth.stmms.biz.lock;

import org.apache.commons.lang.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;

import cn.com.qmth.stmms.biz.lock.impl.MemoryLockProvider;
import cn.com.qmth.stmms.common.enums.LockType;

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

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

    private static final String KEY_JOINER = "_";

    private ApplicationContext context;

    private LockProvider provider;

    public boolean trylock(LockType type, Object... keys) {
        return provider.tryLock(type, getKeys(keys));
    }

    public void waitlock(LockType type, Object... keys) {
        provider.waitLock(type, getKeys(keys));
    }

    public void unlock(LockType type, Object... keys) {
        provider.unlock(type, getKeys(keys));
    }

    public boolean isLocked(LockType type, Object... keys) {
        return provider.isLocked(type, getKeys(keys));
    }

    public void waitUnlock(LockType type, Object... keys) {
        provider.waitUnlock(type, getKeys(keys));
    }

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

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

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