package com.anythink.reactnative.init;

import android.text.TextUtils;

import com.anythink.reactnative.utils.MsgTools;
import com.thinkup.core.api.TUSDK;
import com.thinkup.core.api.TUUserDeviceInfo;

import org.json.JSONObject;

/**
 * Holds the ad-network device / permission policy JSON sent from React Native via
 * {@link ATInitManager#setAdSourcePrivacyPolicy(String)}.
 * <p>
* thinkup (overseas TPN) branch: only applies Core layer {@link TUUserDeviceInfo}, and does not bind domestic network alliance CustomController.
* JSON key aligned with iOS/Unity/anythink branches to facilitate cross-brand API consistency.
 */
public final class AdSourcePrivacyPolicyStore {

    private static volatile String sPolicyJson;

    private AdSourcePrivacyPolicyStore() {
    }

    public static synchronized void setPolicyJson(String json) {
        if (TextUtils.isEmpty(json)) {
            sPolicyJson = null;
            return;
        }
        if (TextUtils.equals(json, sPolicyJson)) {
            return;
        }
        final JSONObject root;
        try {
            root = new JSONObject(json);
        } catch (Throwable t) {
            MsgTools.printMsg("setPolicyJson parse error: " + (t == null ? "" : t.getMessage()));
            return;
        }
        MsgTools.printMsg("setPolicyJson : " + json);
        applyCoreDeviceInfo(root);
        sPolicyJson = json;
    }

    public static String getPolicyJson() {
        return sPolicyJson;
    }

    private static void applyCoreDeviceInfo(JSONObject root) {
        if (root == null) {
            return;
        }
        try {
            TUUserDeviceInfo deviceInfo = new TUUserDeviceInfo();
            deviceInfo.setDevImei(optString(root, Keys.CUSTOM_IMEI));
            deviceInfo.setDevOaid(optString(root, Keys.CUSTOM_OAID));
            TUSDK.setTUUserDeviceInfo(deviceInfo);
        } catch (Throwable t) {
            MsgTools.printMsg("applyCoreDeviceInfo error: " + (t == null ? "" : t.getMessage()));
        }
    }

    private static String optString(JSONObject root, String key) {
        if (root == null || key == null || !root.has(key)) {
            return null;
        }
        String v = root.optString(key, null);
        return TextUtils.isEmpty(v) ? null : v;
    }

    /** JSON keys aligned with iOS ATInitManager / anythink AdSourcePrivacyPolicyStore.Keys. */
    private static final class Keys {
        private Keys() {
        }

        private static final String CUSTOM_IMEI = "customIMEI";
        private static final String CUSTOM_OAID = "customOaid";
    }
}
