package com.tsi.comm.server.repository;

import com.tsi.comm.server.vo.TsiNodeVo;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Getter
@RequiredArgsConstructor
@Component
public class TsiNodeManager {

    private final ConcurrentHashMap<Long, TsiNodeVo> tsiNodeVoMap = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, TsiNodeVo> ipAddrMap = new ConcurrentHashMap<>();

    public TsiNodeVo get(long nodeId) {
        return this.tsiNodeVoMap.get(nodeId);
    }
    public void put(long nodeId, TsiNodeVo vo) {
        this.tsiNodeVoMap.put(nodeId, vo);
    }

    public int size() {
        return this.tsiNodeVoMap.size();
    }

    public TsiNodeVo getIpAddr(String ipAddr) {
        if (ipAddr == null || ipAddr.isEmpty()) {
            return null;
        }
        return this.ipAddrMap.get(ipAddr);
    }
    public void putIpAddr(String ipAddr, TsiNodeVo vo) {
        if (ipAddr == null || ipAddr.isEmpty()) {
            return;
        }
        this.ipAddrMap.put(ipAddr, vo);
    }
    public void removeIpAddr(String ipAddr) {
        if (ipAddr == null || ipAddr.isEmpty()) {
            return;
        }
        this.ipAddrMap.remove(ipAddr);
    }

    public int sizeIpAddr() {
        return this.ipAddrMap.size();
    }

    public boolean containsKey(long key) {
        return this.tsiNodeVoMap.containsKey(key);
    }

    public void beforeLoading() {
        for (Map.Entry<Long, TsiNodeVo> obj : this.tsiNodeVoMap.entrySet()) {
            obj.getValue().setCheckInstalled(false);
        }
    }

    public void afterLoading() {
        for (Map.Entry<Long, TsiNodeVo> obj : this.tsiNodeVoMap.entrySet()) {
            if (obj.getValue().isRegistered()) {
                obj.getValue().setInstalled(obj.getValue().isCheckInstalled());
            }
        }
    }

    public void initDump() {
        for (Map.Entry<Long, TsiNodeVo> obj : this.tsiNodeVoMap.entrySet()) {
            TsiNodeVo node = obj.getValue();
            node.setDump(false);
        }
    }

}
