package com.bcxin.signature.scheduling;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class ScheduleJobAbstract implements ApplicationContextAware {
    protected ApplicationContext applicationContext;

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

    protected <T> T getBean(String name, Class<T> tClass) {
        Map<String, T> dataMap = this.applicationContext.getBeansOfType(tClass);
        String matchedBeanName = dataMap.keySet().stream().filter(ii -> ii.toLowerCase().endsWith(name)).findFirst().orElse(null);

        return dataMap.get(matchedBeanName);
    }

    protected <T> Collection<T> getBeans(Collection<String> names, Class<T> tClass) {
        Map<String, T> dataMap = this.applicationContext.getBeansOfType(tClass);

        Collection<String> matchedBeanNames = dataMap.keySet().stream().filter(ii -> names.stream().anyMatch(ix -> ii.toLowerCase().endsWith(ix)))
                .collect(Collectors.toList());

        return matchedBeanNames.stream().map(ii -> dataMap.get(ii)).filter(ii -> ii != null).collect(Collectors.toList());
    }
}
