import { fromCallback } from 'bluebird';
import { scheduleJob } from 'node-schedule';
import { nowSeconds } from '../pubUtils/timeUtil';
import  { RedlockService } from '../services/redLockService';
interface UserCache {
    time: number;
    lock: any;
}
var userCacheMap = new Map<string, UserCache>();

export function init() {
    scheduleJob('clearDirtyData', "0/5 * * * * *", clearDirtyData);//每个5秒钟，释放redis锁
}
/**
 * 释放锁
 */
export function clearDirtyData() {
    userCacheMap.forEach(function(userCache, key) {
        if(nowSeconds() > userCache.time + 10){
            console.log('show lock =' + JSON.stringify(userCache.lock));
            releaseLock(key);
        }
    })
}
/**
 * 根据key解锁
 * @param lockKey 
 */
export function releaseLock(lockKey: string) {
    var userCache = userCacheMap.get(lockKey);
    if (!!userCache && userCache.lock){
        // unlock your resource when you are done
        userCache.lock.unlock();
    }
    userCacheMap.delete(lockKey);
}


export function setLock(lockKey: string, lock: any){
    userCacheMap.set(lockKey, {lock, time: nowSeconds()})
};

export function getLock(lockKey: string) {
    var userCache = userCacheMap.get(lockKey);
    return !!userCache && !!userCache.lock
}