package com.tsi.comm.server.config;

import com.tsi.comm.server.TsiCommServerApplication;
import com.tsi.comm.server.repository.TsiNodeManager;
import com.tsi.comm.server.vo.TsiNodeVo;
import com.tsi.common.utils.StringUtils;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Properties;

@Slf4j
@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Component
public class TraceConfig {

    private final TsiNodeManager nodeManager;

    private boolean queueReport = false;
    private boolean sessionReport = false;
    private boolean nodeLogging = false;

    private Properties getProperties() {
        String traceFileName = System.getProperty("user.dir") + File.separator + "conf" + File.separator + TsiCommServerApplication.APPLICATION_NAME + "-trace.cfg";
        Properties props = new Properties();
        try {
            FileInputStream in = new FileInputStream(traceFileName);
            props.load(in);
            in.close();
        } catch(Exception e) {
//            log.error("{}.getTraceFileInputStream: Exception1: {}", this.getClass().getSimpleName(), e.toString());
        }
        return props;
    }

    private long getNodeId(String nodeId) {
        try {
            return Long.parseLong(nodeId.trim());
        }
        catch (NumberFormatException e) {
            return -1;
        }
    }

    public void loadTraceInfo() {
        try {
            Properties props = getProperties();

            this.nodeManager.initDump();

            String dumps  = props.getProperty("DUMP",  "").trim();
            if (!dumps.isEmpty()) {
                List<String> regionCds = StringUtils.split(dumps, ",");
                regionCds.forEach(id -> {
                    TsiNodeVo node = this.nodeManager.get(getNodeId(id.trim()));
                    if (node != null) {
                        node.setDump(true);
                    }
                });
            }

            this.sessionReport = props.getProperty("session-report",  "false").trim().equalsIgnoreCase("true");
            this.queueReport = props.getProperty("queue-report",  "false").trim().equalsIgnoreCase("true");
            this.nodeLogging = props.getProperty("node-logging",  "false").trim().equalsIgnoreCase("true");
        }
        catch(Exception e) {
            log.error("{}.loadDebugInfo: Exception2: {}", this.getClass().getSimpleName(), e.toString());
        }
    }

}
