package com.rehome.mqttclienttemperature;


import com.rehome.mqttclienttemperature.service.TemperatureService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;

@EnableJpaAuditing
@EnableScheduling
@EnableAsync
@SpringBootApplication
public class AdminClientTemperatureApplication implements CommandLineRunner, ApplicationContextAware {

    /**
     * 获取Spring框架的上下文
     */
    private ApplicationContext applicationContext;
    /**
     后台接口自动导入
     */
    @Resource
    private TemperatureService temperatureService;

    public static void main(String[] args) {
        SpringApplication.run(AdminClientTemperatureApplication.class, args);
    }

    /**
     * 调用 applicationContext(不能在main中使用,main是static的,不能调用)
     * @param args
     */
    @Override
    public void run(String... args) throws Exception {
        //在这里可以调用applicationContext了
        Map<String, Object> controllers = applicationContext.getBeansWithAnnotation(RequestMapping.class);
        for (Map.Entry<String, Object> entry : controllers.entrySet()) {
            System.out.println("------------------------");
            System.out.println(entry.getKey());//demo1Controller
        }
        try {
            if (temperatureService != null) {
                System.out.println("------------------------");
                System.out.println("TemperatureController is not empty");
                MqttRSAClient client = new MqttRSAClient();
                client.start(temperatureService);
            }else {
                System.out.println("temperatureService is empty");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}