package com.adealink.weparty.location.viewmodel

import android.Manifest
import android.location.Location
import androidx.fragment.app.FragmentActivity
import com.adealink.frame.aab.util.getCompatString
import com.adealink.frame.base.IError
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.locale.location.OnLocationListener
import com.adealink.frame.locale.location.constant.TAG_LOCATION
import com.adealink.frame.log.Log
import com.adealink.weparty.App
import com.adealink.weparty.R
import com.adealink.weparty.location.constant.TAG_LOCATION_REPORT
import com.adealink.weparty.location.data.ReportLocationReq
import com.adealink.weparty.location.datasource.local.LocationLocalService
import com.adealink.weparty.location.datasource.remote.LocationHttpService
import com.adealink.weparty.permission.PermissionUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlin.coroutines.resume

object LocationReporter {

    private val locationHttpService by lazy {
        App.instance.networkService.getHttpService(LocationHttpService::class.java)
    }

    private val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)


    fun reportLocation(activity: FragmentActivity?) {
        activity ?: return
        CoroutineScope(Dispatcher.WENEXT_THREAD_POOL).launch {
            withContext(Dispatcher.UI) {
                App.instance.locationManager.init(activity)
                val granted = requestPermission(activity)
                if (granted) {
                    val location = getLocation()
                    reportLocation(location)
                }
            }
        }
    }

    private suspend fun requestPermission(activity: FragmentActivity): Boolean {
        return suspendCancellableCoroutine { coroutine ->
            if (PermissionUtils.hasPermissions(activity, *permissions)) {
                if (coroutine.isActive) {
                    coroutine.resume(true)
                }
                return@suspendCancellableCoroutine
            }
            if (System.currentTimeMillis() < LocationLocalService.nextPermissionRequestTs) {
                if (coroutine.isActive) {
                    coroutine.resume(false)
                }
                return@suspendCancellableCoroutine
            }
            LocationLocalService.nextPermissionRequestTs =
                System.currentTimeMillis() + 259_200_000 //3天之提醒一次
            PermissionUtils.requestPermissions(
                activity,
                permissions.toList(),
                getCompatString(R.string.common_report_location_request_permission),
                onGranted = {
                    if (coroutine.isActive) {
                        coroutine.resume(true)
                    }
                },
                onDenied = {
                    if (coroutine.isActive) {
                        coroutine.resume(false)
                    }
                }
            )
        }
    }

    private suspend fun getLocation(): Location? {
        return suspendCancellableCoroutine { continuation ->
            App.instance.locationManager.getLocation(object : OnLocationListener {
                override fun onFailed(error: IError) {
                    Log.e(TAG_LOCATION, "getLocation fail, ${error.serverCode}, ${error.msg}")
                }

                override fun onSuccess(location: Location) {
                    Log.d(
                        TAG_LOCATION,
                        "getLocation success, longitude: ${location.longitude}, latitude: ${location.latitude}"
                    )
                    if (continuation.isActive) {
                        continuation.resume(location)
                    }
                }
            })
        }
    }

    private suspend fun reportLocation(location: Location?) {
        Log.d(TAG_LOCATION_REPORT, "reportLocation")
//        var simMcc = ""
//        var simMnc = ""
//        var netMcc = ""
//        var netMnc = ""
//        val simMccMnc: String = getSimOperator()
//        if (simMccMnc.length >= 3) {
//            simMcc = simMccMnc.substring(0, 3)
//        }
//        if (simMccMnc.length >= 4) {
//            simMnc = simMccMnc.substring(3)
//        }
//        val netMccMnc: String = getNetworkOperator()
//        if (netMccMnc.length >= 3) {
//            netMcc = netMccMnc.substring(0, 3)
//        }
//        if (netMccMnc.length >= 5) {
//            netMnc = netMccMnc.substring(3, 5)
//        }
//        val locationInfo = LocationInfo(
//            latitude, longitude,
//            getNewCountryCode(),
//            languageManager?.getLanguageCode() ?: "",
//            simMcc, simMnc, netMcc, netMnc, ""
//        )
        location ?: return
        locationHttpService.reportLocation(
            ReportLocationReq(
                location.latitude,
                location.longitude
            )
        )
    }

}