package com.tsi.comm.server.config;

import com.tsi.app.common.xnet.NettyServerConfig;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

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

    private int maxConnection = 0;
    private boolean loggingThread = false;
    private int packetWorkers = 0;
    private int loggingWorkers = 0;
    private int dbmsWorkers = 0;

    @PostConstruct
    private void init() {

        configure();

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

        log.info("[{}] -------------------------", this.getClass().getSimpleName());
        log.info("[{}]         maxConnection: {}", this.getClass().getSimpleName(), this.maxConnection);
        log.info("[{}]         loggingThread: {}", this.getClass().getSimpleName(), this.loggingThread);
        log.info("[{}]         packetWorkers: {}", this.getClass().getSimpleName(), this.packetWorkers);
        log.info("[{}]        loggingWorkers: {}", this.getClass().getSimpleName(), this.loggingWorkers);
        log.info("{}", super.toString());
    }

    public int getQueueSize() {
        int qSize = 10000;
        if (this.maxConnection == 0)
            qSize = 10000;
        else if (this.maxConnection < 5000)
            qSize = 5000;
        else {
            if (this.maxConnection > qSize)
                qSize = this.maxConnection;
        }
        return qSize;
    }
}
