package tech.starwin.utils;

import android.content.Context;

import com.facebook.FacebookSdk;
import com.facebook.accountkit.internal.AccountKitController;
import com.facebook.accountkit.internal.Initializer;

import java.lang.reflect.Field;

import tech.starwin.BuildConfig;
import tech.starwin.LibConfig;
import tech.starwin.utils.format_utils.StringDecrypt;

public class AccountKitUtils {

    public static boolean initAccountKit(String facebookAppId, String appName, String accoutkitClientToken) {
        try {
            String localAppId = BuildConfig.FACEBOOK_APP_ID;
            String localClienToken = BuildConfig.ACCOUNT_KIT_CLIENT_TOKEN;

            if (localAppId.equals(facebookAppId) && localClienToken.equals(accoutkitClientToken)) {
                return true;
            }
            Class clazz = AccountKitController.class;
            Field initializerField = clazz.getDeclaredField("initializer");
            initializerField.setAccessible(true);
            Initializer initializer = (Initializer) initializerField.get(clazz);
            Field dataFiled = initializer.getClass().getDeclaredField("data");
            dataFiled.setAccessible(true);
            Object data = dataFiled.get(initializer);
            Field applicationIdF = data.getClass().getDeclaredField("applicationId");
            applicationIdF.setAccessible(true);
            Field applicationNameF = data.getClass().getDeclaredField("applicationName");
            applicationNameF.setAccessible(true);
            Field clientTokenF = data.getClass().getDeclaredField("clientToken");
            clientTokenF.setAccessible(true);

            applicationIdF.set(data, facebookAppId);
            applicationNameF.set(data, appName);
            clientTokenF.set(data, accoutkitClientToken);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    public static boolean initFbSdk(Context context,final FacebookSdk.InitializeCallback callback){
        try {
            //反射还原初始化状态
            Class sdkInstance = FacebookSdk.class;
            Field field = sdkInstance.getDeclaredField("sdkInitialized");
            field.setAccessible(true);
            field.set(new FacebookSdk(),false);


            //重新初始化
            FacebookSdk.setApplicationId(BuildConfig.FACEBOOK_APP_ID);
            FacebookSdk.setAutoInitEnabled(true);
            FacebookSdk.sdkInitialize(context,callback);
            return true;
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
}
