@file:Suppress("DEPRECATION")

package com.birdsounds.identify

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Address
import android.location.Geocoder
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import java.util.Locale


object Location {
    private var locationListenerGPS: LocationListener? = null

    fun stopLocation(context: Context) {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (locationListenerGPS != null) locationManager.removeUpdates(
            locationListenerGPS!!
        )
        locationListenerGPS = null
    }

    fun requestLocation(
        context: Context,
        soundClassifier: SoundClassifier,
        soundClassifierSpectrogramBased: SoundClassifierSpectrogramBased
    ) {
        if (ActivityCompat.checkSelfPermission(
                context,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) == PackageManager.PERMISSION_GRANTED && checkLocationProvider(context)
        ) {
            val locationManager =
                context.getSystemService(Context.LOCATION_SERVICE) as LocationManager


            if (locationListenerGPS == null) locationListenerGPS = object : LocationListener {
                @SuppressLint("SetTextI18n")
                override fun onLocationChanged(location: Location) {


                    Log.w(TAG, "Got location changed");
                    while (!soundClassifier.is_model_ready()) {
                        Thread.sleep(50);
                    }
                    Log.w(TAG, "Sound classifier is ready");
                    soundClassifier.runMetaInterpreter(location)

                    Log.w(TAG, "Got location changed");
                    while (!soundClassifierSpectrogramBased.is_model_ready()) {
                        Thread.sleep(50);
                    }
                    Log.w(TAG, "Sound classifier is ready");
                    soundClassifierSpectrogramBased.runMetaInterpreter(location)


                    val activity = context as? Activity;
                    activity?.let {

                        val text_species: TextView = it.findViewById(R.id.local_species)
                        text_species.text = local_species_spectrogram;

                        val loc_lon: TextView = it.findViewById(R.id.location_long)
                        loc_lon.text =
                            "Longitude: ${location.longitude}"

                        val loc_lat: TextView = it.findViewById(R.id.location_lat)
                        loc_lat.text =
                            "Latitude: ${location.latitude}"

                        val loc_string: TextView = it.findViewById(R.id.location_string);
                        val geocoder = Geocoder(context, Locale.getDefault())
                        val addresses: MutableList<Address>? =
                            geocoder.getFromLocation(location.latitude, location.longitude, 1)
                        if (addresses?.isNotEmpty() == true) {
                            val address: Address = addresses[0]
                            loc_string.text = address.getAddressLine(0).toString()
                        }
                    }

                }

                @Deprecated("")
                override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
                }

                override fun onProviderEnabled(provider: String) {
                }

                override fun onProviderDisabled(provider: String) {
                }
            }
            locationManager.requestLocationUpdates(
                LocationManager.PASSIVE_PROVIDER, 60000, 0f,
                locationListenerGPS!!
            )
        }
    }

    fun checkLocationProvider(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            Toast.makeText(context, "Error no GPS", Toast.LENGTH_SHORT).show()
            return false
        } else {
            return true
        }
    }
}