package com.ads.cal.myapplicationc

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.core.app.ActivityCompat
import java.text.DecimalFormat

class Utils(private val locationInterface: LocationInterface) {
    private val handler = Handler(Looper.getMainLooper())
    private var locationManager: LocationManager? = null
    private var isStartingTask = false
    private val dataListeners // 存储监听器列表
            : MutableList<LocationListener>

    init {
        dataListeners = ArrayList() // 初始化监听器列表
    }

    private fun stoAllTaskUpdates() {
        if (dataListeners.isNotEmpty()) {
            for (listener in dataListeners) {
                locationManager!!.removeUpdates(listener) // 停止每个监听器
            }
            dataListeners.clear() // 清空监听器列表
        }
    }

    // 将经纬度格式化为度分秒
    private fun convertToDMS(value: Double, isLatitude: Boolean): Array<String> {
        var data = value
        val degrees = data.toInt()
        data = (data - degrees) * 60
        val minutes = data.toInt()
        data = (data - minutes) * 60
        val seconds = data
        val direction =
            if (isLatitude) (if (data < 0) "West longitude" else "East longitude") else if (data < 0) "South latitude" else "North latitude"
        val decimalFormat = DecimalFormat("00")
        return arrayOf(
            direction,
            degrees.toString() + "°" + decimalFormat.format(minutes.toLong()) + "′" + decimalFormat.format(
                seconds
            ) + "″"
        )
    }

    fun startTask() {
        if (ActivityCompat.checkSelfPermission(
                BaseApplication.context!!,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(
                BaseApplication.context!!,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            // 如果没有定位权限，请求权限
            // 此处可以添加代码来请求权限
            return
        }
        locationManager =
            BaseApplication.context!!.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val list = locationManager!!.getProviders(true)
        if (list.isEmpty()) {
            // 没有可用的定位提供程序
            return
        }
        isStartingTask = true

        // 停止之前的监听器
        stoAllTaskUpdates()
        for (i in list.indices) {
            val location = locationManager!!.getLastKnownLocation(list[i])
            if (location != null) {
                updateLocation(location)
                break
            }
            val locationListener = locationListener
            dataListeners.add(locationListener) // 将监听器添加到列表
            locationManager!!.requestSingleUpdate(list[i], locationListener, null)
        }

        // 使用Handler来延迟停止定位请求
        handler.postDelayed({ stopTask() }, 15000) // 12秒
    }

    private fun updateLocation(location: Location?) {
        if (location != null) {
            val latitude = location.latitude
            val longitude = location.longitude


            // 将经纬度格式化为度分秒
            val formattedLatitude = convertToDMS(latitude, true)
            val formattedLongitude = convertToDMS(longitude, false)

            // 回调接口，将定位数据传递给其他地方
            locationInterface.locationMsgCallBack(formattedLatitude, formattedLongitude)
            locationInterface.locationCallBack(latitude, longitude)
        } else {
            // 定位失败，也需要释放监听
            stopTask()
        }
    }

    fun stopTask() {
        if (isStartingTask) {
            stoAllTaskUpdates() // 停止之前的监听器
            isStartingTask = false
        }
    }

    private val locationListener: LocationListener
        get() = object : LocationListener {
            @Deprecated("Deprecated in Java")
            override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
            override fun onProviderEnabled(provider: String) {}
            override fun onProviderDisabled(provider: String) {
                stopTask()
            }

            override fun onLocationChanged(location: Location) {
                stopTask()
                updateLocation(location)
            }
        }


    interface LocationInterface {
        fun locationMsgCallBack(lat: Array<String>?, log: Array<String>?)
        fun locationCallBack(lat: Double, lon: Double)
    }
}