package study.ready;

import java.nio.file.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import org.springframework.boot.*;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.*;
import org.springframework.boot.web.server.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class ReadinessApp {
  static final List<String> events=new java.util.concurrent.CopyOnWriteArrayList<>();
  public static void main(String[] args){SpringApplication.run(ReadinessApp.class,args);}
  @EventListener void bound(WebServerInitializedEvent event){
    String namespace=event.getApplicationContext().getServerNamespace();
    System.out.println((namespace==null?"BUSINESS_PORT ":"MANAGEMENT_PORT ")+event.getWebServer().getPort());events.add(namespace==null?"business-listening":"management-listening");
  }
  @EventListener void started(ApplicationStartedEvent event){events.add("started");System.out.println("STARTED");}
  @EventListener void ready(ApplicationReadyEvent event){events.add("ready");System.out.println("READY");}
  @Bean ApplicationRunner runner(Environment env){return args->{
    events.add("runner-enter");String file=env.getProperty("lab.release-file");
    if(file!=null){long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);while(!Files.exists(Path.of(file))){if(System.nanoTime()>end)throw new IllegalStateException("controlled runner was not released");Thread.sleep(20);}}
    events.add("runner-exit");System.out.println("RUNNER_EXIT");
  };}
}
