package com.brilliance.isc.common.lock.impl;

import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import com.brilliance.isc.common.lock.BizLocker;
import com.brilliance.isc.common.lock.LockInfo;

public abstract class AbstractBizLocker implements BizLocker {

    private Logger log = LoggerFactory.getLogger(AbstractBizLocker.class);


    private static final Long DEFAULT_LEASE_TIME = 30 * 60L;

    @Override
    public boolean isAccessible(LockInfo lockInfo) {
        LockInfo lockInfo1 =  getLock(lockInfo);
        if(lockInfo1 == null){
            return true;
        }
        String value = lockInfo1.genLockValue();
        if(value == null){
            return true;
        }
        //锁信息相等，且允许重入
        if(value.equalsIgnoreCase(lockInfo.genLockValue()) && value.endsWith("#true")){
            return true;
        }
        log.info("不一致的锁信息{}==={}",lockInfo.genLockValue(),value);
        return false;
    }

    @Override
    public boolean isAccessible(LockInfo lockInfo,String isValid) {
        LockInfo lockInfo1 =  getLock(lockInfo);
        if(lockInfo1 == null){
            return true;
        }
        String value = lockInfo1.genLockValue();
        if(value == null){
            return true;
        }
        //锁信息相等，且允许重入
        if(value.equalsIgnoreCase(lockInfo.genLockValue()) && value.endsWith("#true") && "N".equals(isValid)){
            return true;
        }
        return false;
    }

    @Override
    public boolean lock(LockInfo lockInfo, long seconds) {
        return this.lock(lockInfo.genLockKey(),lockInfo.genLockValue(),seconds);
    }


    @Override
    public boolean lock(LockInfo lockInfo) {
        return this.lock(lockInfo.genLockKey(),lockInfo.genLockValue(),DEFAULT_LEASE_TIME);
    }

    /**
     * 强制加锁
     *
     * @param lockInfo
     * @return
     */
    @Override
    public boolean lockForce(LockInfo lockInfo) {

        return lockForce(lockInfo.genLockKey(),lockInfo.genLockValue(),DEFAULT_LEASE_TIME);
    }
}
