package com.singular.sdk.internal; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import com.amazonaws.handlers.HandlerChainFactory$$ExternalSyntheticThrowCCEIfNotNull0; import com.applovin.impl.sdk.utils.JsonUtils; import com.singular.sdk.SingularConfig; import com.singular.sdk.internal.ApiStartSession; import com.singular.sdk.internal.ApiSubmitEvent; import java.util.HashMap; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; /* loaded from: classes4.dex */ public class SingularInstance { public static SingularInstance instance; public static final SingularLog logger = SingularLog.getLogger("Instance"); public static int retryCounter = 0; public final ApiManager apiManager; public SingularConfig config; public final Context context; public DeviceInfo deviceInfo; public HashMap globalProperties; public boolean initialized = false; public SessionManager sessionManager; public final SingularWorkerThread worker; public static SingularInstance getInstance() { return instance; } public ApiManager getApiManager() { return this.apiManager; } public Context getContext() { return this.context; } public DeviceInfo getDeviceInfo() { return this.deviceInfo; } public SessionManager getSessionManager() { return this.sessionManager; } public SingularConfig getSingularConfig() { return this.config; } public boolean isInitialized() { return this.initialized; } public static SingularInstance getInstance(Context context, SingularConfig singularConfig) { if (instance == null) { synchronized (SingularInstance.class) { try { if (instance == null) { SingularLog.ENABLE_LOGGING = singularConfig.enableLogging; SingularLog.LOG_LEVEL = singularConfig.logLevel; instance = new SingularInstance(context, singularConfig); } } finally { } } } SingularInstance singularInstance = instance; singularInstance.config = singularConfig; return singularInstance; } public SingularInstance(Context context, SingularConfig singularConfig) { SingularLog singularLog = logger; singularLog.debug("SDK version: %s", Constants.SDK_VERSION); singularLog.debug("SDK build info: %s", Constants.SDK_BUILD_INFO); singularLog.debug("new SingularInstance() with config: %s", singularConfig); Context applicationContext = context.getApplicationContext(); if (!(applicationContext instanceof Application)) { throw new IllegalStateException("Context failed to cast to ApplicationContext"); } this.context = applicationContext; this.config = singularConfig; SingularWorkerThread singularWorkerThread = new SingularWorkerThread("worker"); this.worker = singularWorkerThread; ApiManager apiManager = new ApiManager(new SingularWorkerThread("api"), context, new SQLitePersistentQueue(context)); this.apiManager = apiManager; singularWorkerThread.start(); initGlobalProperties(); apiManager.tryMigrateEventsFromFileQueue(); apiManager.tryMigrateEventsFromOldSQLiteQueue(); runOnWorker(new Runnable() { // from class: com.singular.sdk.internal.SingularInstance.1 @Override // java.lang.Runnable public void run() { SingularInstance.this.init(this); } }); } public final void init(SingularInstance singularInstance) { if (isInitialized()) { logger.error("Singular is already initialized, please don't call init() again."); return; } try { singularInstance.deviceInfo = new DeviceInfo(singularInstance.context); DeviceInfo deviceInfo = this.deviceInfo; SingularConfig singularConfig = this.config; deviceInfo.imei = singularConfig.imei; if (singularConfig.wasCustomUserIdSetBeforeInit) { saveCustomUserId(singularConfig.customUserId); } singularInstance.sessionManager = new SessionManager(singularInstance); this.initialized = true; logger.info("Singular is initialized now."); } catch (Exception e) { logger.error("error in init()", e); } } public final void initGlobalProperties() { this.globalProperties = loadGlobalProperties(); if (this.config.globalProperties.size() == 0) { return; } HashMap hashMap = (HashMap) this.globalProperties.clone(); Iterator it = this.config.globalProperties.values().iterator(); if (it.hasNext()) { HandlerChainFactory$$ExternalSyntheticThrowCCEIfNotNull0.m(it.next()); throw null; } if (hashMap.size() > 5) { return; } this.globalProperties = hashMap; saveGlobalProperties(); if (this.globalProperties == null) { clearGlobalProperties(); } } public final boolean isSessionManagerInitialized() { return (!isInitialized() || getInstance() == null || getSessionManager() == null) ? false : true; } public boolean logEvent(String str) { return logEvent(str, null); } public boolean logEvent(String str, String str2) { int length = (str != null ? str.length() : 0) + (str2 != null ? str2.length() : 0); if (length > 3746) { logger.debug("Event discarded! payload length = %d", Integer.valueOf(length)); return false; } logEvent(new ApiSubmitEvent.RawEvent(str, str2)); return true; } public void logEvent(final ApiSubmitEvent.RawEvent rawEvent) { if (isAllTrackingStopped()) { logger.debug("Tracking was stopped! not logging event!"); } else if (!isSessionManagerInitialized()) { retryTask(new Runnable() { // from class: com.singular.sdk.internal.SingularInstance.2 @Override // java.lang.Runnable public void run() { SingularInstance.this.logEvent(rawEvent); } }); } else { runOnWorker(new Runnable() { // from class: com.singular.sdk.internal.SingularInstance.3 @Override // java.lang.Runnable public void run() { ApiSubmitEvent apiSubmitEvent = new ApiSubmitEvent(rawEvent.timestamp); apiSubmitEvent.addParams(ApiSubmitEvent.Params.build(rawEvent, SingularInstance.instance)); SingularInstance.instance.apiManager.enqueue(apiSubmitEvent); } }); } } public void logSessionStart(final long j) { if (isAllTrackingStopped()) { logger.debug("Tracking was stopped! not logging event!"); } else { runOnWorkerAtFront(new Runnable() { // from class: com.singular.sdk.internal.SingularInstance.6 @Override // java.lang.Runnable public void run() { if (SingularInstance.instance != null) { ApiStartSession apiStartSession = new ApiStartSession(j); apiStartSession.addParams(ApiStartSession.Params.build(j, SingularInstance.instance)); SingularInstance.instance.apiManager.enqueue(apiStartSession); SingularInstance.instance.config.openUri = null; } } }); } } public void retryTask(Runnable runnable) { if (retryCounter < 10) { runOnWorkerDelayed(runnable, 200); retryCounter++; } } public void runOnWorker(Runnable runnable) { this.worker.post(runnable); } public void runOnWorkerAtFront(Runnable runnable) { this.worker.postAtFront(runnable); } public void runOnWorkerDelayed(Runnable runnable, int i) { this.worker.postDelayed(runnable, i); } public void startSessionIfOpenedWithDeeplink() { if (this.config.singularLink == null) { return; } runOnWorker(new Runnable() { // from class: com.singular.sdk.internal.SingularInstance.8 @Override // java.lang.Runnable public void run() { SingularInstance.this.sessionManager.startNewSession(Utils.getCurrentTimeMillis()); } }); } public void saveCustomUserId(String str) { SharedPreferences.Editor edit = getContext().getSharedPreferences("singular-pref-session", 0).edit(); edit.putString("custom_user_id", str); edit.commit(); this.deviceInfo.setCustomUserId(str); } public void sendInstallReferrerEvent(String str, String str2, long j, long j2) { try { JSONObject jSONObject = new JSONObject(); jSONObject.put("referrer", str); jSONObject.put("referrer_source", str2); jSONObject.put("clickTimestampSeconds", j); jSONObject.put("installBeginTimestampSeconds", j2); jSONObject.put("current_device_time", Utils.getCurrentTimeMillis()); logEvent(new ApiSubmitEvent.RawEvent("__InstallReferrer", jSONObject.toString())); } catch (JSONException e) { logger.error("error in sendInstallReferrerEvent()", e); } } public boolean isAllTrackingStopped() { return this.context.getSharedPreferences("singular-pref-session", 0).getBoolean("stop_all_tracking", false); } public JSONObject getGlobalPropertiesJSON() { return new JSONObject(this.globalProperties); } public void clearGlobalProperties() { this.globalProperties = null; saveGlobalProperties(); } public final void saveGlobalProperties() { if (this.globalProperties == null) { this.globalProperties = new HashMap(); } SharedPreferences.Editor edit = this.context.getSharedPreferences("singular-pref-session", 0).edit(); edit.putString("global_properties", getGlobalPropertiesJSON().toString()); edit.commit(); } public HashMap loadGlobalProperties() { JSONObject jSONObject; try { jSONObject = new JSONObject(this.context.getSharedPreferences("singular-pref-session", 0).getString("global_properties", JsonUtils.EMPTY_JSON)); } catch (Exception unused) { jSONObject = new JSONObject(); } HashMap hashMap = new HashMap(); Iterator keys = jSONObject.keys(); while (keys.hasNext()) { try { String next = keys.next(); hashMap.put(next, jSONObject.getString(next)); } catch (Exception unused2) { } } return hashMap; } }