package com.utic.center.utic.traf.server.config;

import com.utic.center.common.utils.StringUtils;
import com.utic.center.utic.traf.server.UticTrafServerApplication;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

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

    private Set<String> debugLinks = new HashSet<>();
    private boolean debug = false;

    @PostConstruct
    private void init() {
        loadTraceInfo();
        log.info("TraceConfig.init: debugLinks: {}", this.debugLinks);
        log.info("TraceConfig.init:      debug: {}", this.debug);
    }
    private Properties getProperties() {
        String traceFileName = System.getProperty("user.dir") + File.separator + "conf" + File.separator + UticTrafServerApplication.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;
    }

    public void loadTraceInfo() {
        try {
            this.debugLinks = new HashSet<>();
            Properties props = getProperties();
            String dumps  = props.getProperty("linkIds",  "").trim();
            if (!dumps.isEmpty()) {
                List<String> linkIds = StringUtils.split(dumps, ",");
                this.debugLinks.addAll(linkIds);
            }
            this.debug = props.getProperty("debug",  "false").trim().equalsIgnoreCase("true");
        } catch(Exception e) {
            log.error("{}.loadDebugInfo: Exception2: {}", this.getClass().getSimpleName(), e.toString());
        }
    }

    public boolean isDebugLink(String linkId) {
        if (this.debugLinks == null || this.debugLinks.isEmpty()) {
            return false;
        }
        return this.debugLinks.contains(linkId);
    }
}
