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

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.fq.channel.sdk.base.Exception.NoSuchFunctionException;
import com.fq.channel.sdk.base.interfaces.PluginResult;
import com.fq.channel.sdk.base.interfaces.PluginResultHandler;

import java.util.Map;

public class ApiPlugin extends ApiReflectManager {

	protected String TAG = getClass().getSimpleName() ;


	private static byte[] sync = new byte[0];
	private static ApiPlugin instance = null;

	public static ApiPlugin getInstace() {
		if (instance == null) {
			synchronized (sync) {
				instance = new ApiPlugin();
			}
		}
		return instance;
	}

	private ApiPlugin() {

	}

	Handler mainHandler = new Handler(Looper.getMainLooper());

	public void post(Runnable r) {
		mainHandler.post(r);
	}


	public void init(Context context, PluginResultHandler cb) {
		if(cb == null) {
			Log.e(TAG, "====initialize====的回调函数为null,请初始化");
			return;
		}

		try {
			invoke(getDeclaredMethod("init", Context.class, PluginResultHandler.class),
					context, cb);
		} catch (NoSuchFunctionException e) {
			Log.e(TAG, "initialize NoSuchFunctionException");
			e.printStackTrace();
			cb.onHandlePluginResult(new PluginResult(PluginResult.Status.ERROR));
		}
	}


	public void login(Context context, PluginResultHandler cb) {

		if(cb == null) {
			Log.e(TAG, "====login====的回调函数为null,请初始化");
			return;
		}
		try {
			invoke(getDeclaredMethod("login", Context.class, PluginResultHandler.class),
					context, cb);
		} catch (NoSuchFunctionException e) {
			Log.e(TAG, "login NoSuchFunctionException");
			e.printStackTrace();
			cb.onHandlePluginResult(new PluginResult(PluginResult.Status.ERROR));
		}

	}

	public void pay(Context context,Map map, PluginResultHandler cb) {

		if(cb == null) {
			Log.e(TAG, "====pay====的回调函数为null,请初始化");
			return;
		}
		try {
			invoke(getDeclaredMethod("pay", Context.class,Map.class, PluginResultHandler.class),
					context,map, cb);
		} catch (NoSuchFunctionException e) {
			Log.e(TAG, "login NoSuchFunctionException");
			e.printStackTrace();
			cb.onHandlePluginResult(new PluginResult(PluginResult.Status.ERROR));
		}

	}

}
