package com.tsi.comm.server.config;

import com.tsi.app.common.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();

        if (this.packetWorkers == 0) {
            this.packetWorkers = Runtime.getRuntime().availableProcessors() / 2;
            if (this.packetWorkers == 0) this.packetWorkers = 16;
        }
        if (this.loggingWorkers == 0) {
            this.loggingWorkers = Runtime.getRuntime().availableProcessors() / 4;
            if (this.loggingWorkers == 0) this.loggingWorkers = 4;
        }
        if (this.dbmsWorkers == 0) {
            this.dbmsWorkers = Runtime.getRuntime().availableProcessors() / 4;
            if (this.dbmsWorkers == 0) this.dbmsWorkers = 8;
        }
        if (getReaderIdleTimeSeconds() < 5) {
            setReaderIdleTimeSeconds(5);
        }

        this.whiteListIpSet = getWhitelistIpSet();

        log.info("[{}] -------------------------", this.getClass().getSimpleName());
        log.info("[{}]              serverId: {}", this.getClass().getSimpleName(), this.serverId);
        log.info("[{}]         packetWorkers: {}", this.getClass().getSimpleName(), this.packetWorkers);
        log.info("[{}]        loggingWorkers: {}", this.getClass().getSimpleName(), this.loggingWorkers);
        log.info("[{}]           dbmsWorkers: {}", this.getClass().getSimpleName(), this.dbmsWorkers);
        log.info("[{}]           checkPacket: {}", this.getClass().getSimpleName(), this.checkPacket);
        log.info("[{}]        whiteListIpSet: {}", this.getClass().getSimpleName(), 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);
    }

}
