package com.ysnows.base.ccextension;

import com.billy.cc.core.component.CC;
import com.billy.cc.core.component.IComponent;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Map;

/**
 * 根据actionName寻找方法,并invoke
 */
public class CCExtension {

    public static boolean onCall(IComponent object, CC cc) {
        if (object == null) {
            return false;
        }

        String actionName = cc.getActionName();
        Method[] methods = object.getClass().getDeclaredMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            if (methodName.equals(actionName)) {
                Map<String, Object> params = cc.getParams();
                if (params != null) {
                    Object[] objects = new Object[params.size() + 1];
                    objects[0] = cc;


                    Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
                    for (int j = 1; j < params.size() + 1; j++) {
                        Map.Entry<String, Object> next = iterator.next();
                        objects[j] = next.getValue();
                    }

                    try {
                        return (boolean) method.invoke(object, objects);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }
}
