package com.movesdk import android.app.Activity import android.content.Intent import android.provider.Settings import android.util.Log import com.facebook.react.bridge.ActivityEventListener import com.facebook.react.bridge.Callback import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReadableArray import com.facebook.react.bridge.ReadableMap import com.movesdk.shared.ARGUMENT_STATE import com.movesdk.shared.BATTERY_OPTIMIZATION_REQUEST_CODE import com.movesdk.shared.EVENT_AUTH_BATTERY_PERMISSION import com.movesdk.shared.EVENT_AUTH_OVERLAY_PERMISSION import com.movesdk.shared.LOG_TAG import com.movesdk.shared.OVERLAY_REQUEST_CODE import io.dolphin.move.MoveSdk import io.dolphin.move.MoveServiceWarning class MoveSdkModule internal constructor(context: ReactApplicationContext) : NativeMoveSdkSpec(context), ActivityEventListener { companion object { const val NAME = "MoveSdk" } private val reactContext: ReactApplicationContext = context private val nativeSdkWrapper = NativeMoveSdkWrapper.getInstance(context) init { nativeSdkWrapper.applyDelegate(this) // **** PERMISSIONS MODULE START ***** reactContext.addActivityEventListener(this) // **** PERMISSIONS MODULE START ***** } override fun getName(): String { return NAME } override fun addListener(eventType: String?) { eventType ?: return // Posted, not inline: RN calls this before registering the JS subscription. reactContext.runOnJSQueueThread { nativeSdkWrapper.replayPendingEvent(eventType) } } override fun removeListeners(count: Double) { // Remove upstream listeners, stop unnecessary background tasks } override fun cancelTimer(key: String?) { nativeSdkWrapper.cancelTimer(key = key) } override fun canDrawOverlays(promise: Promise) { promise.resolve(Settings.canDrawOverlays(reactContext)) } override fun finishCurrentTrip() { nativeSdkWrapper.finishCurrentTrip() } override fun forceTripRecognition(duration: Double) { nativeSdkWrapper.forceTripRecognition(duration.toLong()) } override fun getAuthState(promise: Promise) { nativeSdkWrapper.getAuthState(promise) } override fun getBluetoothPermission(promise: Promise) { promise.resolve(nativeSdkWrapper.hasDiscoveryPermissions()) } override fun getBluetoothState(promise: Promise) { promise.resolve(nativeSdkWrapper.isBluetoothEnabled()) } override fun getDeviceQualifier(promise: Promise) { promise.resolve(nativeSdkWrapper.getDeviceQualifier()) } override fun getErrors(promise: Promise?) { nativeSdkWrapper.getErrors(promise) } override fun geocode( latitude: Double, longitude: Double, promise: Promise ) { nativeSdkWrapper.geocode(latitude, longitude, promise) } override fun getRegisteredDevices(promise: Promise) { nativeSdkWrapper.getRegisteredDevices(promise) } override fun getState(promise: Promise) { nativeSdkWrapper.getState(promise) } override fun getTripState(promise: Promise) { nativeSdkWrapper.getTripState(promise) } override fun getWarnings(promise: Promise) { val warnings: List = nativeSdkWrapper.getWarnings() ?: emptyList() promise.resolve(warnings.warningsToArray().toWritableArray()) } override fun ignoreCurrentTrip() { nativeSdkWrapper.ignoreCurrentTrip() } override fun initiateAssistanceCall(promise: Promise) { nativeSdkWrapper.initiateAssistanceCall(promise) } override fun isAppIgnoringBatteryOptimization(promise: Promise?) { promise?.resolve(reactContext.isAppIgnoringBatteryOptimization()) } override fun requestAppIgnoringBatteryOptimization() { nativeSdkWrapper.requestAppIgnoringBatteryOptimization(reactContext) } override fun isAuthValid(promise: Promise) { nativeSdkWrapper.isAuthValid(promise) } override fun keepActive(enabled: Boolean) { nativeSdkWrapper.keepActive(enabled) } override fun keepInForeground(enabled: Boolean) { nativeSdkWrapper.keepInForeground(enabled) } override fun mockLocations(allow: Boolean) { nativeSdkWrapper.allowMockLocations(allow) } override fun registerDevices( devices: ReadableArray?, promise: Promise ) { try { nativeSdkWrapper.registerDevices( rawData = devices?.toArrayList() as? ArrayList>, promise = promise, ) } catch (t: Throwable) { Log.e("SDK Module", t.message, t) } } override fun requestBluetoothAlwaysUsagePermission() { // Stub } override fun requestDrawOverlaysPermission() { nativeSdkWrapper.requestDrawOverlaysPermission(reactContext) } override fun requestMotionPermission() { // Stub } override fun resolveError() { nativeSdkWrapper.resolveError() } override fun setAssistanceMetaData(data: String?) { nativeSdkWrapper.setAssistanceMetaData(data) } override fun setLiveLocationTag( tag: String?, promise: Promise? ) { if (nativeSdkWrapper.setLiveLocationTag(tag)) { promise?.resolve(true) } else { promise?.reject(Exception("Can't set location tag, check Move SDK logs for more information")) } } override fun setTimer(delay: Double, key: String, callback: Callback) { nativeSdkWrapper.setTimer( delay = delay.toInt(), key = key, callback = callback ) } override fun setTripMetadata(metadata: ReadableMap?) { val metadataMap = metadata?.toHashMap()?.mapValues { it.value.toString() } nativeSdkWrapper.setTripMetadata(metadataMap) } override fun setup( auth: ReadableMap?, config: ReadableMap?, options: ReadableMap?, platformParams: ReadableArray?, promise: Promise? ) { try { val authMap = auth?.toHashMap() ?: throw IllegalArgumentException("Auth object is null") val userId = authMap["userId"] as String val accessToken = authMap["accessToken"] as String val refreshToken = authMap["refreshToken"] as String val projectId = authMap["projectId"] as Double config ?: throw IllegalArgumentException("Config object is null") val timelineDetectionServices = config.getArray("timelineDetectionServices")!! val drivingServices = config.getArray("drivingServices")!! val walkingServices = config.getArray("walkingServices")!! val platformParamsIterator = platformParams?.toArrayList()?.iterator() ?: throw IllegalArgumentException("Platform Params object is null") val recognitionNotificationTitle = platformParamsIterator.next() as String val recognitionNotificationText = platformParamsIterator.next() as String val tripNotificationTitle = platformParamsIterator.next() as String val tripNotificationText = platformParamsIterator.next() as String nativeSdkWrapper.setup( userId = userId, accessToken = accessToken, refreshToken = refreshToken, projectId = projectId.toInt(), timelineDetectionServices = timelineDetectionServices, drivingServices = drivingServices, walkingServices = walkingServices, options = options, recognitionNotificationTitle = recognitionNotificationTitle, recognitionNotificationText = recognitionNotificationText, tripNotificationTitle = tripNotificationTitle, tripNotificationText = tripNotificationText, promise = promise ) } catch (e: Exception) { Log.e(LOG_TAG, "Error during setup", e) } } override fun setupWithCode( code: String?, config: ReadableMap?, options: ReadableMap?, platformParams: ReadableArray?, promise: Promise? ) { try { code ?: throw IllegalArgumentException("Code is null") config ?: throw IllegalArgumentException("Config object is null") val timelineDetectionServices = config.getArray("timelineDetectionServices")!! val drivingServices = config.getArray("drivingServices")!! val walkingServices = config.getArray("walkingServices")!! val platformParamsIterator = platformParams?.toArrayList()?.iterator() ?: throw IllegalArgumentException("Platform Params object is null") val recognitionNotificationTitle = platformParamsIterator.next() as String val recognitionNotificationText = platformParamsIterator.next() as String val tripNotificationTitle = platformParamsIterator.next() as String val tripNotificationText = platformParamsIterator.next() as String nativeSdkWrapper.setup( code = code, timelineDetectionServices = timelineDetectionServices, drivingServices = drivingServices, walkingServices = walkingServices, options = options, recognitionNotificationTitle = recognitionNotificationTitle, recognitionNotificationText = recognitionNotificationText, tripNotificationTitle = tripNotificationTitle, tripNotificationText = tripNotificationText, promise = promise ) } catch (e: Exception) { Log.e(LOG_TAG, "Error during setup", e) } } override fun shutdown(force: Boolean, timeout: Double?, promise: Promise?) { nativeSdkWrapper.shutdown(force = force == true, timeout = timeout?.toInt(), promise = promise) } override fun startAutomaticDetection(promise: Promise?) { promise?.resolve(nativeSdkWrapper.startAutomaticDetection()) } override fun startScanningDevices( filter: ReadableArray?, uuid: String?, manufacturerId: Double? ) { Log.i("MODULE_SCAN_DEVICE", "startScanningDevices: ${filter}") val filters = try { filter?.toArrayList()?.map { it.toString() }.orEmpty() } catch (e: Exception) { emptyList() } nativeSdkWrapper.startScanningDevices(filters, manufacturerId?.toInt(), uuid) } override fun startTrip( metadata: ReadableMap?, promise: Promise? ) { val metadataMap = metadata?.toHashMap()?.mapValues { it.value.toString() } promise?.resolve(MoveSdk.get()?.startTrip(metadataMap) == true) } override fun stopAutomaticDetection(promise: Promise?) { promise?.resolve(nativeSdkWrapper.stopAutomaticDetection()) } override fun stopScanningDevices() { nativeSdkWrapper.stopScanningDevices() } override fun synchronizeUserData(promise: Promise) { nativeSdkWrapper.synchronizeUserData(promise) } override fun unregisterDevices( devices: ReadableArray?, promise: Promise ) { try { nativeSdkWrapper.unregisterDevices( rawData = devices?.toArrayList() as? ArrayList>, promise = promise, ) } catch (t: Throwable) { Log.e("SDK Module", t.message, t) } } override fun updateAuth( auth: ReadableMap?, promise: Promise? ) { try { val authMap = auth?.toHashMap() ?: throw IllegalArgumentException("Auth object is null") val contractId = authMap["contractId"] as String val accessToken = authMap["accessToken"] as String val refreshToken = authMap["refreshToken"] as String val productId = authMap["productId"] as Int nativeSdkWrapper.updateAuth(contractId, accessToken, refreshToken, productId) } catch (e: Exception) { Log.e(LOG_TAG, "Error updating auth", e) } } override fun updateConfig( config: ReadableMap?, options: ReadableMap? ) { try { nativeSdkWrapper.updateConfig( timelineDetectionServices = config?.getArray("timelineDetectionServices")!!, drivingServices = config.getArray("drivingServices")!!, walkingServices = config.getArray("walkingServices")!!, options ) } catch (e: Exception) { Log.e(LOG_TAG, "Error updating config", e) } } fun emitDeviceEvent(eventName: String, data: Array) { reactContext.emitDeviceArrayEvent(eventName, data) } fun emitDeviceEvent(eventName: String, data: Map<*, *>) { reactContext.emitDeviceMapEvent(eventName, data) } fun emitDeviceEvent(eventName: String, data: String) { reactContext.emitDeviceStringEvent(eventName, data) } override fun onActivityResult( activity: Activity, requestCode: Int, resultCode: Int, data: Intent? ) { if (requestCode == OVERLAY_REQUEST_CODE) { val eventData = mutableMapOf() eventData[ARGUMENT_STATE] = Settings.canDrawOverlays(reactContext) emitDeviceEvent(EVENT_AUTH_OVERLAY_PERMISSION, eventData) } else if (requestCode == BATTERY_OPTIMIZATION_REQUEST_CODE) { val eventData = mutableMapOf() eventData[ARGUMENT_STATE] = reactContext.isAppIgnoringBatteryOptimization() emitDeviceEvent(EVENT_AUTH_BATTERY_PERMISSION, eventData) } } override fun onNewIntent(intent: Intent) { // Stub } override fun getConstants(): Map? { val constants = mutableMapOf() constants["version"] = MoveSdk.version return constants.toMap() } override fun startNativeSdkStateListener() { nativeSdkWrapper.addSdkStateListener() } override fun requestHealthPermissions(promise: Promise?) { nativeSdkWrapper.requestHealthPermissions(promise) } override fun getMoveConfig(promise: Promise?) { nativeSdkWrapper.getMoveConfig(promise) } }