package com.example.vnote_device_plugin.utils;

import android.app.Application;

import java.lang.reflect.Method;

import io.flutter.Log;
import io.flutter.plugin.common.MethodCall;
import  io.flutter.plugin.common.MethodChannel.Result;

/**
 * 公共工具类
 */
public class CommonUtils {
    /**
     * 通用方法，获得参数值，如未找到参数，则直接中断
     */
    public static <T> T getParam(MethodCall methodCall, Result result, String param) {
        T parameter = methodCall.argument(param);
        if (parameter == null) {
            result.error("Missing parameter", "Cannot find parameter `" + param + "` or `" + param + "` is null!", 5);
        }
        return parameter;
    }

    /**
     * 通用方法，获得参数值，参数可以为null
     */
    public static <T> T getParamNullable(MethodCall methodCall, Result result, String param) {
        T parameter = methodCall.argument(param);
        return parameter;
    }

    /**
     * 获取当前应用的Application
     * 先使用ActivityThread里获取Application的方法，如果没有获取到，
     * 再使用AppGlobals里面的获取Application的方法
     *
     * @return
     */
    public static Application getCurApplication() {
        Application application = null;
        try {
            Class atClass = Class.forName("android.app.ActivityThread");
            Method currentApplicationMethod = atClass.getDeclaredMethod("currentApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
            Log.d("fw_create", "curApp class1:" + application);
        } catch (Exception e) {
            Log.d("fw_create", "e:" + e.toString());
        }

        if (application != null)
            return application;

        try {
            Class atClass = Class.forName("android.app.AppGlobals");
            Method currentApplicationMethod = atClass.getDeclaredMethod("getInitialApplication");
            currentApplicationMethod.setAccessible(true);
            application = (Application) currentApplicationMethod.invoke(null);
            Log.d("fw_create", "curApp class2:" + application);
        } catch (Exception e) {
            Log.d("fw_create", "e:" + e.toString());
        }

        return application;
    }

}
