package app.klottr.location import kotlinx.cinterop.ExperimentalForeignApi import kotlinx.cinterop.useContents import kotlinx.coroutines.* import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import platform.CoreLocation.* import platform.Foundation.NSError import platform.Foundation.timeIntervalSince1970 import platform.darwin.NSObject private class IOSLocationService( private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Default) ) : NSObject(), LocationService, CLLocationManagerDelegateProtocol { private val manager = CLLocationManager() private val _location = MutableStateFlow(null) override val location: StateFlow = _location private var started = false private var highAccuracy = true init { manager.delegate = this } override fun start(updates: LocationUpdates) { if (started) return started = true highAccuracy = updates.highAccuracy manager.desiredAccuracy = if (updates.highAccuracy) kCLLocationAccuracyBest else kCLLocationAccuracyHundredMeters manager.distanceFilter = kCLDistanceFilterNone when (CLLocationManager.authorizationStatus()) { kCLAuthorizationStatusNotDetermined -> manager.requestWhenInUseAuthorization() else -> {} } manager.startUpdatingLocation() } override fun stop() { if (!started) return manager.stopUpdatingLocation() started = false } override suspend fun current(highAccuracy: Boolean, timeoutMillis: Long): GeoPoint? { // On iOS, startUpdatingLocation yields callbacks; just return latest within timeout. if (!started) start(LocationUpdates(highAccuracy = highAccuracy)) return try { withTimeout(timeoutMillis) { while (_location.value == null) delay(50) _location.value } } catch (_: Throwable) { _location.value ?: LastLocationStore.lastKnownLocation.value } } override suspend fun isLocationEnabled(): Boolean { return CLLocationManager.locationServicesEnabled() } // CLLocationManagerDelegate @OptIn(ExperimentalForeignApi::class) override fun locationManager(manager: CLLocationManager, didUpdateLocations: List<*>) { val last = (didUpdateLocations.lastOrNull() as? CLLocation) ?: return val ts = last.timestamp.timeIntervalSince1970() * 1000.0 last.coordinate.useContents { val lat = latitude val lon = longitude val p = GeoPoint( lat = lat, lon = lon, accuracyMeters = last.horizontalAccuracy, timeMillis = ts.toLong() ) _location.value = p LastLocationStore.update(p) } } override fun locationManager(manager: CLLocationManager, didFailWithError: NSError) { /* ignore */ } } actual object LocationServiceProvider { private val instance: LocationService by lazy { IOSLocationService() } actual fun get(): LocationService = instance }