package com.elab.spring.design.group;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class GroupInvocationManager implements InitializingBean {

    @Autowired
    private List<GroupRouteInvocation> groupRouteInvocationList;

    private Map<String, Map<String, GroupRouteInvocation>> groupMap = new HashMap<>();

    public List<GroupRouteInvocation> getInvocationList(String groupName) {
        Map<String, GroupRouteInvocation> groupRouteInvocationMap = groupMap.get(groupName);

        if (groupRouteInvocationMap == null) {
            return null;
        }
        return groupRouteInvocationMap.values().stream().collect(Collectors.toList());
    }

    public GroupRouteInvocation getInvocation(String groupName, String key) {
        Map<String, GroupRouteInvocation> groupRouteInvocationMap = groupMap.get(groupName);
        if (groupRouteInvocationMap != null) {
            return groupRouteInvocationMap.get(key);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (this.groupRouteInvocationList != null) {
            this.groupRouteInvocationList.forEach(obj -> {
                Map<String, GroupRouteInvocation> routeInvocationMap = groupMap.get(obj.groupName());
                if (routeInvocationMap == null) {
                    routeInvocationMap = new HashMap<>();
                    groupMap.put(obj.groupName(), routeInvocationMap);
                }

                if (obj.unionKey() != null) {
                    routeInvocationMap.put(obj.unionKey(), obj);
                }
            });
        }
    }
}
