package cn.ibizlab.util.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class LockService {


    @Autowired
    @Lazy
    private LockService proxy;

    @Cacheable( value="lock", key = "'key:'+#p0")
    public synchronized Long getLock(String key)
    {
        long lockTime=System.currentTimeMillis();
        System.out.println("lockTime"+lockTime);
        return lockTime;
    }

    @Cacheable( value="lock", key = "'key:'+#p0")
    public Long resetLock(String key,Long newLockTime)
    {
        return newLockTime;
    }

    @CacheEvict( value="lock", key = "'key:'+#p0")
    public void deleteLock(String key)
    {

    }

    public synchronized boolean isLocked(String key,Long lockTimeMillis)
    {
        if(StringUtils.isEmpty(key))
            return false;
        Long now=System.currentTimeMillis();

        Long lockTime=proxy.getLock(key);

        System.out.println(lockTime+":"+now);
        if(lockTime>=now)
            return false;

        if(lockTime+lockTimeMillis<now)
        {
            proxy.deleteLock(key);
            proxy.resetLock(key,now);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    proxy.resetLock(key,now);
                }
            }).start();
            return false;
        }

        return true;
    }

    public void unLock(String key)
    {
        proxy.deleteLock(key);
    }

}
