package cc.smtweb.framework.core;

import cc.smtweb.framework.core.common.SwConsts;
import cc.smtweb.framework.core.mvc.controller.IStartListener;
import cc.smtweb.framework.core.mvc.controller.scan.ApplicationScanner;
import cc.smtweb.framework.core.mvc.controller.scan.BeanManager;
import cc.smtweb.framework.core.systask.SysServiceFactory;
import cc.smtweb.framework.core.systask.WebStartedEvent;
import lombok.SneakyThrows;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.List;

/**
 * 执行接口扫描任务
 */
@Component
@Order(SwConsts.DEFAULT_ORDER)
public class CoreApplicationStartedListener implements ApplicationListener<ApplicationStartedEvent> {
    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("onApplicationEvent=============");
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();

        //包扫描
        ApplicationScanner.scan(applicationContext);

        List<IStartListener> list = BeanManager.getInstance().getStartListeners();
        list.sort(Comparator.comparingInt(IStartListener::order));
        for (IStartListener sl : list) {
            sl.init();
        }
        for (IStartListener sl : list) {
            sl.run();
        }
        SysServiceFactory.getInstance().start();
        // 通知 controller 正式使用
        applicationContext.publishEvent(new WebStartedEvent());
        SwConsts.SysParam.SYS_STARTED = true;
        System.out.println("start end=============");
    }
}
