package com.dxareactnative.navigation import android.util.Log import com.dxareactnative.DxaReactNativeModule import com.facebook.react.bridge.ReadableMap import com.qualtrics.dxa.ScreenChangeType import com.qualtrics.dxa.ScreenDetectionType import com.qualtrics.dxa.ScreenHierarchyElement private const val TAG = DxaReactNativeModule.TAG internal fun parseScreenChangePayload(screenChangePayload: ReadableMap?): Triple, ScreenChangeType, ScreenDetectionType>? { try { if (screenChangePayload == null) { throw IllegalArgumentException("Payload cannot be null.") } val screenHierarchy = parseScreenHierarchyFromPayload(screenChangePayload) val changeType = parseChangeTypeFromPayload(screenChangePayload) val detectionType = parseDetectionTypeFromPayload(screenChangePayload) return Triple(screenHierarchy, changeType, detectionType) } catch (e: IllegalArgumentException) { Log.e(TAG, "Failed to parse screenChangePayload: ${e.message}") return null } } private fun parseScreenHierarchyFromPayload(screenChangePayload: ReadableMap): List { val rawScreenHierarchy = screenChangePayload.getArray("screenHierarchy") ?: throw IllegalArgumentException("Missing required field 'screenHierarchy'.") if (rawScreenHierarchy.size() == 0) { throw IllegalArgumentException("Invalid screenHierarchy: Array cannot be empty.") } val parsedScreenHierarchy = mutableListOf() for (i in 0 until rawScreenHierarchy.size()) { val rawElement = rawScreenHierarchy.getMap(i) ?: throw IllegalArgumentException("Invalid screenHierarchyElement at index $i: Element is null or not an object.") val screenName = rawElement.getString("screenName") ?.takeIf { it.isNotEmpty() } ?: throw IllegalArgumentException("Invalid screenHierarchyElement at index $i: Element is missing required field 'screenName' or it's empty.") val screenType = rawElement.getString("screenType") ?.takeIf { it.isNotEmpty() } ?: "screen" parsedScreenHierarchy.add(ScreenHierarchyElement(screenName, screenType)) } return parsedScreenHierarchy } private fun parseChangeTypeFromPayload(screenChangePayload: ReadableMap): ScreenChangeType { val changeType = screenChangePayload.getString("changeType") ?: throw IllegalArgumentException("Missing required field 'changeType'.") return when (changeType) { "appear" -> ScreenChangeType.APPEAR "disappear" -> ScreenChangeType.DISAPPEAR else -> throw IllegalArgumentException("Field changeType: Expected 'appear' or 'disappear' but received '$changeType'.") } } private fun parseDetectionTypeFromPayload(screenChangePayload: ReadableMap): ScreenDetectionType { val detectionType = screenChangePayload.getString("detectionType") ?: throw IllegalArgumentException("Missing required field 'detectionType'.") return when (detectionType) { "auto" -> ScreenDetectionType.AUTO "manual" -> ScreenDetectionType.MANUAL else -> throw IllegalArgumentException("Field detectionType: Expected 'auto' or 'manual' but received '$detectionType'.") } }