package tech.starwin.utils;

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

import java.lang.reflect.Field;

public class AccountKitUtils {

    public static boolean initAccountKit(String facebookAppId, String appName, String accoutkitClientToken) {
        try {
            if (facebookAppId.equals(PreferencesManager.get().getAccountAppId()) && accoutkitClientToken.equals(PreferencesManager.get().getAccountKitToken())) {
                return false;
            }
            PreferencesManager.get().saveAccountAppId(facebookAppId);
            PreferencesManager.get().saveAccountKitToken(accoutkitClientToken);

            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;
    }
}
