package xyz.wbsite.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.type.filter.AssignableTypeFilter;
import xyz.wbsite.frame.schedule.RunTask;
import xyz.wbsite.frame.schedule.Scheduler;
import xyz.wbsite.frame.utils.LogUtil;

import javax.annotation.PostConstruct;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Configuration
public class TaskConfig {

    @Autowired
    private Scheduler scheduler;

    @Bean
    public Scheduler registerScheduler() {
        return new Scheduler();
    }

    @PostConstruct
    public void registryTask() {
        {// 扫描类任务
            String aPackage = this.getClass().getPackage().getName();
            Pattern compile = Pattern.compile("(.*)\\.config");
            Matcher matcher = compile.matcher(aPackage);
            if (matcher.find()) {
                DefaultListableBeanFactory simpleBeanDefinitionRegistry = new DefaultListableBeanFactory();
                ClassPathBeanDefinitionScanner classPathBeanDefinitionScanner = new ClassPathBeanDefinitionScanner(simpleBeanDefinitionRegistry);
                classPathBeanDefinitionScanner.resetFilters(false);
                classPathBeanDefinitionScanner.addIncludeFilter(new AssignableTypeFilter(RunTask.class));
                classPathBeanDefinitionScanner.setBeanNameGenerator(new BeanNameGenerator() {
                    @Override
                    public String generateBeanName(BeanDefinition beanDefinition, BeanDefinitionRegistry beanDefinitionRegistry) {
                        String beanClassName = beanDefinition.getBeanClassName();
                        try {
                            Class<?> aClass = Class.forName(beanClassName);
                            Object instance = aClass.newInstance();
                            RunTask task = (RunTask) instance;
                            scheduler.createOrRepeat(task);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtil.i("registry task " + beanClassName);
                        return beanClassName;
                    }
                });
                classPathBeanDefinitionScanner.scan(matcher.group(1));
            }
        }

    }
}