package com.friday.dynamic.config;

import com.friday.dynamic.core.ModuleService;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置入口
 */
@Configuration
@Slf4j
public class DynamicConfig {

    @Value("${dynamic.jar:/}")
    private String dynamicJar;

    @Autowired
    private ModuleService moduleService;

    @Bean
    @ConditionalOnProperty(prefix = "dynamic",name = "jar")
    public ApplicationListener listener() {
        return (ApplicationListener<ApplicationStartedEvent>) event -> {
			File file = new File(dynamicJar);
			if (!file.exists()) {
				log.error("当前路径下没有对应jar包，jar包加载失败！");
				return;
			}
			for (File module : file.listFiles()) {
				if (module.isDirectory()) {
					try {
						moduleService.manualLoadAndRegister(module.getAbsolutePath());
						log.info("启动成功！");
					} catch (Exception e) {
						log.error("启动时加载jar包失败", e);
					}
				}
			}
        };
    }


}
