package de.jadehs.strassenschadenpro2

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import java.net.HttpURLConnection
import java.net.URL

class ListViewModel(application: Application): AndroidViewModel(application) {

    private val _features = MutableStateFlow<List<Feature>>(emptyList())
    val features: StateFlow<List<Feature>> = _features

    fun fetch() {
        viewModelScope.launch {
            try {
                val data =
                    loadFeatures("https://services9.arcgis.com/UVxdrlZq3S3gqt7w/ArcGIS/rest/services/StrassenSchaeden/FeatureServer/0/query?where=1%3D1&objectIds=&geometry=&geometryType=esriGeometryEnvelope&inSR=&spatialRel=esriSpatialRelIntersects&resultType=none&distance=0.0&units=esriSRUnit_Meter&outDistance=&relationParam=&returnGeodetic=false&outFields=OBJECTID%2Ctyp%2Cbeschreibung&returnGeometry=true&featureEncoding=esriDefault&multipatchOption=xyFootprint&maxAllowableOffset=&geometryPrecision=&outSR=&defaultSR=&datumTransformation=&applyVCSProjection=false&returnIdsOnly=false&returnUniqueIdsOnly=false&returnCountOnly=false&returnExtentOnly=false&returnQueryGeometry=false&returnDistinctValues=false&cacheHint=false&collation=&orderByFields=&groupByFieldsForStatistics=&returnAggIds=false&outStatistics=&having=&resultOffset=&resultRecordCount=&returnZ=false&returnM=false&returnTrueCurves=false&returnExceededLimitFeatures=true&quantizationParameters=&sqlFormat=none&f=pgeojson&token=")
                _features.value = data.features
            } catch (e: Exception){
                e.printStackTrace()
            }
        }

    }

    suspend fun loadFeatures(url: String): FeatureCollection {
        val jsonParser = Json { ignoreUnknownKeys = true }
        val jsonText = loadJsonFromUrl(url)
        return jsonParser.decodeFromString(jsonText)
    }

    suspend fun loadJsonFromUrl(urlString: String): String{
        return withContext(Dispatchers.IO){
            val url = URL(urlString)
            val conn = url.openConnection() as HttpURLConnection
            conn.requestMethod = "GET"
            conn.connectTimeout = 5000
            conn.readTimeout = 5000

            try {
                val stream = conn.inputStream
                stream.bufferedReader().use { it.readText() }
            } finally {
                conn.disconnect()
            }
        }
    }
}

@Serializable
data class FeatureCollection(
    val type: String? = null,
    val features: List<Feature> = emptyList()
)

@Serializable
data class Feature(
    val type: String? = null,
    val id: Int? = null,
    val geometry: Geometry? = null,
    val properties: Properties? = null
)

@Serializable
data class Geometry(
    val type: String? = null,
    val coordinates: List<Double> = emptyList()
)

@Serializable
data class Properties(
    val OBJECTID: Int? = null,
    val Typ: String? = null,
    val Beschreibung: String? = null
)






















