package com.tsi.comm.server.config;

import com.tsi.comm.server.xnet.NettyServerConfig;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Slf4j
@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "application.cvim-server")
public class TsiCvimServerConfig extends NettyServerConfig {

    private int serverId = 0;
    private int packetWorkers = 0;
    private int loggingWorkers = 0;
    private int dbmsWorkers = 0;
    private boolean checkPacket = true;
    private List<String> whiteListIps = new ArrayList<>();
    private Set<String> whiteListIpSet = new HashSet<>();
    private boolean startup = false;

    @PostConstruct
    private void init() {

        configure();

        int MAX_CORE = Math.max(8, Runtime.getRuntime().availableProcessors());

        if (this.packetWorkers == 0) {
            this.packetWorkers = MAX_CORE / 2;
        }
        if (this.loggingWorkers == 0) {
            this.loggingWorkers = MAX_CORE / 4;
        }
        if (this.dbmsWorkers == 0) {
            this.dbmsWorkers = MAX_CORE / 4;
        }

        if (getReaderIdleTimeSeconds() < 5) {
            setReaderIdleTimeSeconds(5);
        }

        this.whiteListIpSet = getWhitelistIpSet();

        log.info("[TsiCvimServerConfig] -------------------------");
        log.info("[TsiCvimServerConfig]              serverId: {}", this.serverId);
        log.info("[TsiCvimServerConfig]              MAX_CORE: {}", MAX_CORE);
        log.info("[TsiCvimServerConfig]         packetWorkers: {}", this.packetWorkers);
        log.info("[TsiCvimServerConfig]        loggingWorkers: {}", this.loggingWorkers);
        log.info("[TsiCvimServerConfig]           dbmsWorkers: {}", this.dbmsWorkers);
        log.info("[TsiCvimServerConfig]           checkPacket: {}", this.checkPacket);
        log.info("[TsiCvimServerConfig]        whiteListIpSet: {}", this.whiteListIpSet);
        log.info("{}", super.toString());
    }

    public Set<String> getWhitelistIpSet() {
        if (this.whiteListIps == null) {
            return Collections.emptySet();
        } else {
            return new HashSet<>(this.whiteListIps);
        }
    }

    public boolean isInWhitelistIps(String ip) {
        return this.whiteListIpSet.contains(ip);
    }

}
