package cn.myapps.scheduler;

import cn.myapps.common.util.StringUtil;
import cn.myapps.common.util.cache.ICacheProvider;
import cn.myapps.common.util.cache.IMyCache;
import cn.myapps.common.util.cache.IMyElement;
import cn.myapps.common.util.cache.MyCacheManager;
import cn.myapps.runtime.scheduler.ejb.TriggerVO;

import java.util.Date;

public class SchedulerLock {

    public static void lock(TriggerVO vo) throws Exception {
        if(vo!=null&&!StringUtil.isBlank(vo.getToken())){
            ICacheProvider provider = MyCacheManager.getProviderInstance("cn.myapps.util.cache.RedisProvider");
            String cacheName = "SCHEDULERSPACE$"+vo.getId();
            IMyCache cache = provider.getCache(cacheName);
            if (cache == null ) {
                //不存入硬盘，10s失效
                cache = provider.createCache(cacheName, 50000, false, false, 120, 120);
            }
            cache.put(vo.getToken(), (new Date()).getTime()+5*60*1000);
            System.out.println("vo = [" + vo + "]");
        }
    }

    public static void unLock(TriggerVO vo){
        if(vo!=null&&!StringUtil.isBlank(vo.getToken())){
            ICacheProvider provider = MyCacheManager.getProviderInstance("cn.myapps.util.cache.RedisProvider");
            String cacheName = "SCHEDULERSPACE$"+vo.getId();
            IMyCache cache = provider.getCache(cacheName);
            if (cache == null ) {
                return;
            }else {
                cache.remove(vo.getToken());
            }
        }
    }

    public static boolean isLock(TriggerVO vo){
        if(vo!=null&&!StringUtil.isBlank(vo.getToken())){
            ICacheProvider provider = MyCacheManager.getProviderInstance("cn.myapps.util.cache.RedisProvider");
            String cacheName = "SCHEDULERSPACE$"+vo.getId();
            IMyCache cache = provider.getCache(cacheName);
            if (cache == null ) {
                return false;
            }else {
                IMyElement cachedElement = (IMyElement) cache.get(vo.getToken());
                if (cachedElement!=null) {
                    long value = (long) cachedElement.getValue();
                    if(value>(new Date()).getTime()){
                        return true;
                    }else {
                        return false;
                    }
                }else {
                    return false;
                }
            }
        }
        return false;
    }

}
