package egovframework.com.its.web.server;

import egovframework.com.its.web.server.config.ApplicationConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.ApplicationPidFileWriter;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;

import java.text.SimpleDateFormat;
import java.util.Date;

@SpringBootApplication
@Slf4j
public class ItsWebServerApplication extends SpringBootServletInitializer
		implements CommandLineRunner, ApplicationListener<ContextClosedEvent>, InitializingBean, DisposableBean {
	private static final String applicationName = "its-web-server";

	@Autowired
	ApplicationConfig applicationConfig;

	public ItsWebServerApplication() {
		super();
		setRegisterErrorPageFilter(false);
	}

	public static void main(String[] args) {
		SpringApplication springApplication = new SpringApplicationBuilder()
				.sources(ItsWebServerApplication.class)
				.listeners(new ApplicationPidFileWriter("./conf/" + applicationName + ".pid"))
				.build();
		springApplication.setBannerMode(Banner.Mode.OFF);
		springApplication.run(args);
	}

	@Override
	public void run(String... args) {
		log.info("");
		log.info("");
		log.info("************************************************************************************");
		log.info("**                                                                                **");
		log.info("**                         Intelligent Traffic System                             **");
		log.info("**              Intelligent Traffic System Common Operating Server.               **");
		log.info("**                                                                                **");
		log.info("**                                                                   [ver.1.0]    **");
		log.info("** process: {}", applicationConfig.getId());
		log.info("** startup: {}", applicationConfig.getBootingDateTime());
		log.info("************************************************************************************");

	}

	@Override
	public void destroy() {

	}

	@Override
	public void afterPropertiesSet() {

	}

	@Override
	public void onApplicationEvent(ContextClosedEvent event) {
		SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		log.error("Application Terminated: {}, {}", sdfDate.format(new Date()), event.toString());
	}
}
