package com.hzya.frame.util;

import com.hzya.frame.base.PluginBaseEntity;
import com.hzya.frame.web.action.ApplicationContextUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 框架外接插件工具类
 *
 * @Author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @Date 2023-08-02 11:37
 * @Version 1.0
 */
public class PluginUtils {
    private static List<PluginBaseEntity> pluginBeansList;

    static {
        if (pluginBeansList == null) {
            pluginBeansList = getPlugins();
        }
    }

    public static List<PluginBaseEntity> getPlugins() {
        Map<String, PluginBaseEntity> beans = ApplicationContextUtil.getBeansOfType(PluginBaseEntity.class);
        List<Map.Entry<String, PluginBaseEntity>> list = new ArrayList<>(beans.entrySet());
        List<PluginBaseEntity> list1 = new ArrayList<PluginBaseEntity>();
        Iterator<Map.Entry<String, PluginBaseEntity>> in = list.iterator();
        while (in.hasNext()) {
            Map.Entry<String, PluginBaseEntity> entityEntry = in.next();
            list1.add(entityEntry.getValue());
        }
        return list1;
    }

    public static List<PluginBaseEntity> getPluginsByType(String type) {

        List<PluginBaseEntity> pluginBaseEntityList = pluginBeansList.stream().filter(pl -> type.equalsIgnoreCase(pl.getPluginType())).collect(Collectors.toList());
        return pluginBaseEntityList;
    }

    public static PluginBaseEntity getPluginsById(String pluginId) {
        PluginBaseEntity pluginBaseEntity = null;
        if (pluginId != null && !"".equals(pluginId)) {
            for (int i = 0; i < pluginBeansList.size(); i++) {
                if (pluginId.equals(pluginBeansList.get(i).getPluginId())) {
                    pluginBaseEntity = pluginBeansList.get(i);
                }
            }
        }

        return pluginBaseEntity;
    }
}
