package com.yeejoin.amos.boot.module.app.biz.strategy;

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

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class SearchDetailStrategyContext implements ApplicationContextAware {

    private static final Map<String, ISearchDetailHandler> handlerMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, ISearchDetailHandler> searchHandlerMap = applicationContext.getBeansOfType(ISearchDetailHandler.class);
        if (searchHandlerMap.isEmpty()) {
            return;
        }
        for (ISearchDetailHandler handler : searchHandlerMap.values()) {
            handlerMap.put(handler.manageType(), handler);
        }

    }

    public static ISearchDetailHandler getHandler(String type) {
        return Optional.ofNullable(handlerMap.get(type)).orElseThrow(() -> new RuntimeException(String.format("not found %s type strategy", type)));
    }
}
