package com.zd.forward.component;

import com.zd.common.core.utils.Assert;
import com.zd.forward.config.AlgorithmYml;
import com.zd.forward.serivce.CheckResultValid;
import com.zd.forward.serivce.VideoCheckResultValid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

@Component
public class AppStartedListener implements ApplicationListener<ApplicationStartedEvent> {
    Logger logger = LoggerFactory.getLogger(AppStartedListener.class);
    @Autowired
    AlgorithmYml algorithmYml;


    @Override
    public void onApplicationEvent(@NonNull ApplicationStartedEvent applicationStartedEvent) {
        //日志地址验证
        URL url;
        InputStream in = null;
        try {
            url = new URL(algorithmYml.getLoginUri() + algorithmYml.getCheckLogUrl());
            //联通性测试
            in = url.openStream();
            logger.info("检查日志地址连通性测试通过！");
        } catch (MalformedURLException e) {
            logger.error("关闭项目！！！!！！检查日志地址配置错误url：{}", algorithmYml.getCheckLogUrl());
            //关闭服务
            applicationStartedEvent.getApplicationContext().close();
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("检查日志地址连通性测试失败！url:{},请检查实验室项目是否正常，或url配置是否正确！", algorithmYml.getCheckLogUrl());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //算法解析类配置
        logger.info("开始注入算法结果解析");
        //注入
        algorithmYml.getAlgorithmMap().forEach((key, value) -> {
            try {
                Class<?> classPath = value.getClassPath();
                boolean assignableFrom = CheckResultValid.class.isAssignableFrom(value.getClassPath());
                Assert.isTrue(assignableFrom, "算法解析实现类错误！必须是CheckResultValid的实现类");
                boolean b = applicationStartedEvent.getApplicationContext().getBeanFactory().containsBean(classPath.getName());
                logger.info("bean:{},是否存在:{}", classPath.getName(), b);
                if (b) {
                    Object bean = applicationStartedEvent.getApplicationContext().getBeanFactory().getBean(classPath.getName());
                    value.setCheckResultValid((CheckResultValid) bean);
                    return;
                }
                Object o = value.getClassPath().newInstance();
                //注入IOC容器
                applicationStartedEvent.getApplicationContext().getBeanFactory().registerSingleton(classPath.getName(), o);
                //设置
                value.setCheckResultValid((CheckResultValid) o);
            } catch (Exception e) {
                logger.error("算法结果解析注入失败!");
                e.printStackTrace();
                logger.error("关闭项目！！！!请检查算法结果解析配置！！");
                //关闭服务
                applicationStartedEvent.getApplicationContext().close();
            }


        });
        algorithmYml.getVideoAidMap().forEach((key, value) -> {
            try {
                String name = value.getName();

                boolean b = applicationStartedEvent.getApplicationContext().getBeanFactory().containsBean(name);
                logger.info("bean:{},是否存在:{}", name, b);
                if (!b) {
                    logger.error("bean:{},未被注入", name);
                }
                Object bean = applicationStartedEvent.getApplicationContext().getBeanFactory().getBean(name);
                value.setVideoCheckResultValid((VideoCheckResultValid) bean);

            } catch (Exception e) {
                logger.error("视频算法结果解析注入失败!");
                e.printStackTrace();
                logger.error("关闭项目！！！!请检查算法结果解析配置！！");
                //关闭服务
                applicationStartedEvent.getApplicationContext().close();
            }
        });
    }
}
