package cn.meowrain.aioj.backend.framework.core.banner;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.lang.management.ManagementFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
@Deprecated
public class EnvironmentBanner implements ApplicationListener<ApplicationReadyEvent> {

	@Value("${spring.application.name:unknown}")
	private String appName;

	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {

		Environment env = event.getApplicationContext().getEnvironment();

		// Active profiles
		String profiles = String.join(",", env.getActiveProfiles());
		if (profiles.isEmpty()) {
			profiles = "default";
		}

		// Port
		String port = env.getProperty("server.port", "unknown");

		// JVM info
		String jvm = System.getProperty("java.version") + " (" + System.getProperty("java.vendor") + ")";

		// PID
		String pid = ManagementFactory.getRuntimeMXBean().getPid() + "";

		// Time
		String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

		// Git commit id (如果没有 git.properties，不会报错)
		String gitCommit = env.getProperty("git.commit.id.abbrev", "N/A");

		printBanner(appName, profiles, port, jvm, pid, time, gitCommit);
	}

	private void printBanner(String appName, String profiles, String port, String jvm, String pid, String time,
			String gitCommit) {

		String banner = "\n" + "------------------------------------------------------------\n"
				+ "  ✨AI Online Judge✨ - " + appName + "\n" + "  Environment : " + profiles + "\n" + "  Port        : "
				+ port + "\n" + "  Git Commit  : " + gitCommit + "\n" + "  JVM         : " + jvm + "\n"
				+ "  PID         : " + pid + "\n" + "  Started At  : " + time + "\n"
				+ "------------------------------------------------------------\n";
		System.out.println(banner);
	}

}
