package com.huiju.estateagents.common;

import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Hashtable;

@Slf4j
@Component
@EnableScheduling
public class LoginLocker {
    // 锁定时长 分钟
    public static final int lockTime = 5;

    Hashtable<String, LogInfo> allLogs = new Hashtable<>();

    public LogInfo get(String name) {
        return allLogs.get(name);
    }

    public LogInfo add(String name) {
        if (null == name) {
            return null;
        }

        LogInfo logInfo = allLogs.get(name);
        if (null == logInfo) {
            logInfo = new LogInfo()
                    .setKey(name)
                    .setTimes(1)
                    .setExpire(LocalDateTime.now().plusMinutes(lockTime));
            allLogs.put(name, logInfo);
        } else {
            logInfo.setTimes(logInfo.getTimes() + 1)
                    .setExpire(LocalDateTime.now().plusMinutes(lockTime));
        }

        return logInfo;
    }

    public void remove(String name) {
        try {
            allLogs.remove(name);
        } catch (Exception e) {}
    }

    private boolean checkExpire(LogInfo log) {
        return LocalDateTime.now().isAfter(log.getExpire());
    }

    /**
     * 定时任务 每分钟 清除一次不用的缓存
     */
    @Scheduled(fixedRate = 1000 * 60)
    public void clearUnused() {
        for (LogInfo log: allLogs.values()) {
            if (checkExpire(log)) {
                allLogs.remove(log.getKey());
            }
        }
    }

    @Data
    @Accessors(chain = true)
    public static class LogInfo {
        String key;
        int times;
        LocalDateTime expire;
    }
}
