package com.cm.smartgate.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: SmartGateManager
 * @Description: 智慧闸机管理器
 * @Author: WangGeng
 * @Date: 2020/8/27 15:03
 * @Version: 1.0
 **/
public class SmartGateManager {

    private static SmartGateManager smartGateManager = SmartGateManagerBuilder.smartGateManager;
    private Map<String, SmartGateOnlineBO> onlineSmartGate = new ConcurrentHashMap<>();
    private int offLineSecond = 30;

    private SmartGateManager() {
    }

    public static SmartGateManager getInstance() {
        return smartGateManager;
    }

    /**
     * 更新设备在线时间
     *
     * @param smartGateId
     * @param smartGateSerialNo
     */
    public void updateSmartGateManager(String smartGateId, String smartGateSerialNo) {
        SmartGateOnlineBO smartGateOnlineBO = onlineSmartGate.get("smartGateSerialNo");
        if (smartGateOnlineBO == null) {
            smartGateOnlineBO = new SmartGateOnlineBO();
            smartGateOnlineBO.setSmartGateId(smartGateId);
            smartGateOnlineBO.setSmartGateSerialNo(smartGateSerialNo);
            onlineSmartGate.put(smartGateSerialNo, smartGateOnlineBO);
        }
        smartGateOnlineBO.setLastOnlineTime(System.currentTimeMillis());
    }

    /**
     * 设备列表
     *
     * @return
     */
    public List<SmartGateOnlineBO> listSmartGate() {
        List<SmartGateOnlineBO> smartGateOnlineBOs = new ArrayList<>();
        for (Map.Entry<String, SmartGateOnlineBO> kv : onlineSmartGate.entrySet()) {
            smartGateOnlineBOs.add(kv.getValue());
        }
        return smartGateOnlineBOs;
    }

    /**
     * 判断设备是否离线
     *
     * @param smartGateOnlineBO
     * @return
     */
    public boolean isGateOffline(SmartGateOnlineBO smartGateOnlineBO) {
        if (System.currentTimeMillis() - smartGateOnlineBO.getLastOnlineTime() > offLineSecond * 1000) {
            return true;
        }
        return false;
    }

    private static class SmartGateManagerBuilder {
        public static final SmartGateManager smartGateManager = new SmartGateManager();
    }

}
