package org.pupes.mhdrunpathfinder import android.app.Activity import android.os.Handler import android.os.Looper import android.widget.Toast import kotlinx.serialization.json.Json import okhttp3.OkHttpClient import ovh.plrapps.mapcompose.api.moveMarker import java.net.URL // OkHttpClient for making HTTP requests val httpClient = OkHttpClient.Builder() .build() private val HaukMainHandler = Handler(Looper.getMainLooper()) private var HaukTrackingThread: Thread? = null private var HaukIsTracking = false private fun fetchHaukPosition(haukUrl: String, callee: Activity) { try { val url = URL(haukUrl) val targetId = url.toString().substringAfter("?") val request = okhttp3.Request.Builder() .url("${url.protocol}://${url.host}/api/fetch.php?id=$targetId") .header("User-Agent", "${BuildConfig.APPLICATION_ID}/${BuildConfig.VERSION_NAME} (Android)") .build() httpClient.newCall(request).execute().use { response -> var message = if (response.isSuccessful) { response.body?.string() ?: "Empty response" } else { "Error: ${response.code} ${response.message}" } message = "{" + message.substringAfter("{"); val hauk_response = Json.decodeFromString(message) HaukMainHandler.post { mapState.moveMarker("target_position", x = longitudeToXNormalized(hauk_response.points.last()[1]), y = latitudeToYNormalized(hauk_response.points.last()[0])) } } } catch (e: Exception) { // Post UI update to main thread HaukMainHandler.post { Toast.makeText(callee, e.message ?: "Unknown error", Toast.LENGTH_LONG).show() } } } // Start the timer with a URL: fun startHaukTracking(url: String, callee: Activity) { if (HaukIsTracking) return HaukIsTracking = true HaukTrackingThread = Thread { while (HaukIsTracking) { fetchHaukPosition(url, callee) try { Thread.sleep(1000) // Wait 1 second between requests } catch (e: InterruptedException) { break } } }.apply { start() } } fun stopHaukTracking() { HaukIsTracking = false HaukTrackingThread?.interrupt() HaukTrackingThread = null }