package de.jadehs.strassenschadenpro2

import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.location.Priority
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.net.URL

class LocationService: Service() {

    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var locationCallback: LocationCallback

    private val channelID = "1"
    private val notificationID = 1

    override fun onBind(p0: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        locationCallback = object: LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult){
                for (location in locationResult.locations){
                    val latitude = location.latitude
                    val longitude = location.longitude
                    val sharedPreferences=getSharedPreferences("settings", Context.MODE_PRIVATE)
                    val radius= sharedPreferences.getInt("radius", 50)
                    Log.e("LocationService", "Location: $latitude, $longitude")
                    CoroutineScope(Dispatchers.IO).launch {
                        val urlString = "https://services9.arcgis.com/UVxdrlZq3S3gqt7w/ArcGIS/rest/services/StrassenSchaeden/FeatureServer/0/query?where=1%3D1&objectIds=&geometry=$longitude%2C$latitude&geometryType=esriGeometryPoint&inSR=4326&spatialRel=esriSpatialRelIntersects&resultType=none&distance=$radius&units=esriSRUnit_Meter&outDistance=&relationParam=&returnGeodetic=false&outFields=&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="
                        val jsonString = URL(urlString).readText()
                        val jsonObject = JSONObject(jsonString)
                        val features = jsonObject.getJSONArray("features")
                        val anzahl = features.length()
                        if (anzahl > 0){
                            showNotification(this@LocationService, anzahl)
                        }
                    }
                }
            }
        }
    }

    fun showNotification(context: Context, anzahl: Int){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val serviceChannel = NotificationChannel(
                channelID,
                "Location Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(serviceChannel)

            val notification = NotificationCompat.Builder(context, channelID)
                .setContentTitle("Straßenschaden gefunden!")
                .setContentText("$anzahl Strassenschäden gefunden!")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSmallIcon(R.drawable.outline_adb_24)
                .build()
            with(NotificationManagerCompat.from(context)){
                notify(notificationID, notification)
            }
        }
    }

    override fun onStartCommand(intent: Intent?,flags: Int,startId: Int): Int {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val serviceChannel = NotificationChannel(
                channelID,
                "Location Service Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            val manager = getSystemService(NotificationManager::class.java)
            manager?.createNotificationChannel(serviceChannel)
        }
        val notification = NotificationCompat.Builder(this, channelID)
            .setContentTitle("Location Service")
            .setContentText("Running...")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .build()
        startForeground(notificationID, notification)
        val locationRequest = LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY,60000).apply {
            setMinUpdateIntervalMillis(30000)
        }.build()
        fusedLocationClient.requestLocationUpdates(locationRequest,locationCallback, Looper.getMainLooper())

        return START_STICKY
    }
}


















