package com.casic.detector.utils

import android.content.Context
import android.location.Location
import android.util.Log
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.services.core.AMapException
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.GeocodeResult
import com.amap.api.services.geocoder.GeocodeSearch
import com.amap.api.services.geocoder.RegeocodeQuery
import com.amap.api.services.geocoder.RegeocodeResult
import com.casic.detector.callback.IAddressListener
import com.casic.detector.callback.ILocationListener

class LocationHub constructor(context: Context) {

    private val kTag = "LocationHub"
    private val locationClient by lazy { AMapLocationClient(context) }
    private val codeSearch by lazy { GeocodeSearch(context) }

    fun getCurrentLocation(isOnceLocation: Boolean, listener: ILocationListener) {
        val locationOption = AMapLocationClientOption()
        locationOption.locationMode = AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
        locationOption.isOnceLocation = isOnceLocation
        locationClient.setLocationOption(locationOption)
        locationClient.setLocationListener {
            if (it.errorCode == 0) {
                listener.onAMapLocationGet(it)
            } else {
                listener.onAMapLocationGet(null)
                Log.e(
                    kTag, "location Error, ErrCode:${it.errorCode}, errInfo:${it.errorInfo}"
                )
            }
        }
        locationClient.startLocation()
    }

    fun antiCodingLocation(location: Location, listener: IAddressListener) {
        try {
            // 第一个参数表示一个LatLonPoint，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            val query = RegeocodeQuery(
                LatLonPoint(location.latitude, location.longitude), 10f, GeocodeSearch.AMAP
            )
            codeSearch.getFromLocationAsyn(query)
            codeSearch.setOnGeocodeSearchListener(object : GeocodeSearch.OnGeocodeSearchListener {
                override fun onRegeocodeSearched(regeocodeResult: RegeocodeResult, i: Int) {
                    listener.onGetAddress(regeocodeResult.regeocodeAddress.formatAddress)
                }

                override fun onGeocodeSearched(geocodeResult: GeocodeResult?, i: Int) {}
            })
        } catch (e: AMapException) {
            e.printStackTrace()
        }
    }

    fun stopLocation() {
        locationClient.stopLocation()
    }
}