package com.fq.channel.sdk.core.invoke;

import android.util.Log;

import com.fq.channel.sdk.base.exception.NoSuchFunctionException;
import com.fq.channel.sdk.core.JointManager;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 获取渠道插件信息
 *
 * @Author: FLuty
 * @CreateDate: 2020/3/24 17:59
 */
public class ApiReflectManager {
	private String TAG = getClass().getSimpleName();
	private Class<?> mClazz;
	private Object mObject;
	
	public List<String> getMethodNames() {
		List<String> list = new ArrayList<String>();
		try {
			Method[] methods = (ApiPlugin.getInstace().getClass()).getDeclaredMethods();
			for (Method m : methods) {
				if (Modifier.PUBLIC == m.getModifiers()) {
					list.add(m.getName());
				}
			}
		} catch (Exception e) {
		}
		return list;
	}

	public String getClassName() {
		return JointManager.getInstance().getPluginSdkClassName();
	}
	
	Object invoke(Method method, Object... args)  throws NoSuchFunctionException {
		
		if(null == method) {
			throw new NoSuchFunctionException("该渠道还未实现此方法!");
		}
		
		try {
			return method.invoke(mObject, args);
		} catch (Exception e) {
			e.printStackTrace();
			throw new NoSuchFunctionException("该渠道还未实现此方法!");
		}
	}

	Method getDeclaredMethod(String name, Class<?>... parameterTypes) {
		try {
			
			if(null == mClazz) {
				init();
			}
			
			return mClazz.getDeclaredMethod(name, parameterTypes);
		} catch (Exception e) {
			e.printStackTrace();
			Log.d(TAG, name + " is not found.");
		}
		return null;
	}
	
	public void init() {
		try {
			mClazz = Class.forName(getClassName());
			mObject = mClazz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("className:" + getClassName()
					+ " happen exception");
		}
	}
}
