// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: AGPL-3.0-or-later

package xyz.apiote.bimba.czwek.api

import android.content.Context
import android.os.Build
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import xyz.apiote.bimba.czwek.R
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

suspend fun askTransitous(context: Context, json: String): Result {
	return withContext(Dispatchers.IO) {
		val url = URL("https://routing.spline.de/api/")
		val c = (url.openConnection() as HttpURLConnection).apply {
			setRequestProperty(
				"User-Agent",
				"${context.getString(R.string.applicationId)}/${context.getString(R.string.versionName)} (${Build.VERSION.SDK_INT})"
			)
			addRequestProperty("Content-Type", "application/json")
			requestMethod = "POST"
			doOutput = true
			outputStream.write(json.toByteArray())
		}
		try {
			if (c.responseCode == 200) {
				Result(c.inputStream, null)
			} else {
				val (string, image) = mapHttpError(c.responseCode)
				Result(c.errorStream, Error(c.responseCode, string, image))
			}
		} catch (e: IOException) {
			Result(null, Error(0, R.string.error_connecting, R.drawable.error_server))
		}
	}
}
