package com.tofly.codegen.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Administrator
 * @date 2019/9/29  10:44
 */
@Component
@Slf4j
public class MyCodeGenRun implements ApplicationRunner, ApplicationListener<WebServerInitializedEvent> {

    private int serverPort;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("-----------开始执行");

        // 启动后访问地址
        String url = "http://127.0.0.1:"+serverPort+"/code";
        log.info("Portboy准备就绪 ... 启动浏览器"+url);
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("启动出错：{}",e.getMessage());
        }
    }

    @Override
    public void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {
        this.serverPort = webServerInitializedEvent.getWebServer().getPort();
    }
}
