package com.qmth.boot.core.security.config;

import com.qmth.boot.core.security.annotation.AuthorizationComponent;
import com.qmth.boot.core.security.service.AuthorizationService;
import com.qmth.boot.core.security.service.impl.BaseAuthorizationSupport;
import com.qmth.boot.tools.signature.SignatureType;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class SecurityContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private BaseAuthorizationSupport baseAuthorizationSupport;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        //注意 需要时根容器才能通过注解获取到bean，比如event直接获取的容器中只有一些公共注册bean
        if (applicationContext.getParent() != null) {
            applicationContext = applicationContext.getParent();
        }
        Map<String, Object> beansWithAnnotation = applicationContext
                .getBeansWithAnnotation(AuthorizationComponent.class);
        for (Map.Entry<String, Object> entry : beansWithAnnotation.entrySet()) {
            AuthorizationComponent annotation = applicationContext
                    .findAnnotationOnBean(entry.getKey(), AuthorizationComponent.class);
            if (annotation != null && entry.getValue() instanceof AuthorizationService) {
                if (annotation.type().length > 0) {
                    for (SignatureType type : annotation.type()) {
                        register((AuthorizationService) entry.getValue(), annotation.prefix(), type);
                    }
                } else {
                    register((AuthorizationService) entry.getValue(), annotation.prefix(), null);
                }
            }
        }
    }

    private void register(AuthorizationService bean, String[] prefixs, SignatureType type) {
        if (prefixs.length > 0) {
            for (String prefix : prefixs) {
                if (type != null) {
                    baseAuthorizationSupport.getServiceContainer().setPrefix(prefix, type, bean);
                } else {
                    baseAuthorizationSupport.getServiceContainer().setPrefix(prefix, bean);
                }
            }
        } else {
            if (type != null) {
                baseAuthorizationSupport.getServiceContainer().setDefault(type, bean);
            } else {
                baseAuthorizationSupport.getServiceContainer().setDefault(bean);
            }
        }
    }
}
