import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL
// Hardal event tracking implementation for Android (Kotlin)
class HardalTracker {
companion object {
private const val TAG = "HardalTracker"
fun sendEvent(
hardalCustomUrl: String,
signalId: String,
eventName: String,
eventData: Map<String, Any> = emptyMap()
) {
GlobalScope.launch(Dispatchers.IO) {
try {
// Create URL
val url = URL("https://$hardalCustomUrl/push/hardal")
// Open connection
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Content-Type", "application/json")
connection.doOutput = true
// Create payload
val payloadJson = JSONObject().apply {
put("name", eventName)
put("website", signalId)
put("data", JSONObject(eventData))
}
// Create body
val bodyJson = JSONObject().apply {
put("type", "event")
put("payload", payloadJson)
}
// Write body to connection
connection.outputStream.use { os ->
os.write(bodyJson.toString().toByteArray())
}
// Get response
val responseCode = connection.responseCode
if (responseCode in 200..299) {
Log.d(TAG, "Event sent successfully")
} else {
Log.e(TAG, "Failed to send event: $responseCode")
}
connection.disconnect()
} catch (e: Exception) {
Log.e(TAG, "Exception when sending event: ${e.message}", e)
}
}
}
}
}