package cn.reghao.tnb.content.app.config;

import cn.reghao.jutil.jdk.machine.id.MachineId;
import cn.reghao.jutil.jdk.machine.id.MachineIdLinux;
import cn.reghao.tnb.common.prop.LogProperties;
import cn.reghao.tnb.log.Appenders;
import cn.reghao.tnb.log.LoggerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author reghao
 * @date 2022-03-28 11:54:49
 */
@Slf4j
@Component
public class SpringLifecycle implements ApplicationRunner, DisposableBean {
    private final Environment env;
    private final MachineId machineId;
    private final LogProperties logProperties;

    public SpringLifecycle(Environment env, LogProperties logProperties) {
        this.env = env;
        this.machineId = new MachineIdLinux();
        this.logProperties = logProperties;
    }

    @Override
    public void run(ApplicationArguments args) {
        if (logProperties.getEnabled()) {
            initLogConfig();
        }
        log.info("ContentService 启动...");
    }

    private void initLogConfig() {
        String wsUrl = logProperties.getWsUrl();
        if (wsUrl != null) {
            String token = logProperties.getToken();
            String app = env.getProperty("spring.application.name");
            String host = machineId.ipv4();
            String url = String.format("%s?token=%s&app=%s&host=%s", wsUrl, token, app, host);
            LoggerConfig.initLogger(List.of(Appenders.wsAppender(url, app, host)));
        }
    }

    @Override
    public void destroy() {
        log.info("ContentService 停止...");
    }
}
