package com.base.scanqrclear.ui.earthquake

import android.annotation.SuppressLint
import androidx.activity.addCallback
import androidx.core.view.updatePadding
import com.base.scanqrclear.R
import com.base.scanqrclear.ads.AdsMgr
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.base.BaseActivity
import com.base.scanqrclear.bean.EarthquakeData
import com.base.scanqrclear.databinding.ActivityEarthquakeBinding
import com.base.scanqrclear.utils.BarUtils
import com.base.scanqrclear.utils.KotlinExt.toFormatTime3
import com.base.scanqrclear.utils.LogEx
import com.google.gson.Gson
import com.gyf.immersionbar.ktx.immersionBar
import okhttp3.OkHttpClient
import okhttp3.Request
import java.text.DecimalFormat

class EarthquakeActivity : BaseActivity<ActivityEarthquakeBinding>(ActivityEarthquakeBinding::inflate) {

    @SuppressLint("SetTextI18n", "MissingPermission")
    override fun initView() {
        super.initView()
        binding.clTop.updatePadding(top = BarUtils.getStatusBarHeight())

        AdsMgr.showNative(binding.flAd, R.layout.layout_admob_item)
        AdsMgr.showInsert(this, false, object : AdsShowCallBack() {
            override fun close(where: Int) {
            }

            override fun failed(where: Int) {
            }

            override fun googleFailed(where: Int) {
            }
        })

        Thread {
            val data = fetchEarthquakeData()
            val oneData = data?.features?.maxBy { it.properties.sig }
            oneData?.let {
                runOnUiThread {
                    kotlin.runCatching {
                        binding.tvWhere.text = it.properties.place
                        binding.tvTime.text = it.properties.time.toFormatTime3()
                        binding.tvLevel.text = "Level " + "${it.properties.mag}"

                        val ss = it.geometry.coordinates[2]
                        LogEx.logDebug(TAG, "ss=$ss")
                        if (ss < 0.01f) {
                            binding.tvDepth.text = "0.1 Kilometers"
                        } else {
                            val df = DecimalFormat("#.00")
                            val depth = df.format(ss)
                            binding.tvDepth.text = "$depth Kilometers"
                        }

                        binding.tvLongitudeLatitude.text =
                            "[ ${it.geometry.coordinates[0]},${it.geometry.coordinates[1]} ]"

                        binding.tvSignificance.text = it.properties.sig.toString()
                        binding.tvTypes.text = it.properties.types.removePrefix(",").removeSuffix(",")
                    }
                }
            }
        }.start()

//        launcher.launch(
//            arrayOf(
//                android.Manifest.permission.ACCESS_COARSE_LOCATION,
//                android.Manifest.permission.LOCATION_HARDWARE,
//            )
//        ) {
//            val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
//
//            locationManager.requestLocationUpdates(
//                LocationManager.NETWORK_PROVIDER,
//                0L,
//                0f
//            ) { location ->
//                LogEx.logDebug(TAG, "${location.altitude} ${location.longitude}")
//            }
//        }
    }

    override fun initListener() {
        super.initListener()
        onBackPressedDispatcher.addCallback {
            finish()
        }
        binding.flBack.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
    }

    override fun configSystemBar() {
        immersionBar {
            statusBarColor("#00FFFFFF")
            statusBarDarkFont(false)
        }
    }


    private fun haversineDistance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
        val R = 6371 // 地球半径，单位：千米
        val latDistance = Math.toRadians(lat2 - lat1)
        val lonDistance = Math.toRadians(lon2 - lon1)
        val a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2)
        val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        return R * c // 返回距离，单位：千米
    }

    companion object {

        fun fetchEarthquakeData(): EarthquakeData? {
            try {
                val client = OkHttpClient()
                val request = Request.Builder()
                    .url("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson")
                    .build()

                val response = client.newCall(request).execute()

                val responseBody = response.body?.string()

                if (responseBody == null) {
//                    LogEx.logDebug(TAG, "responseBody=null")
                    return null
                } else {
                    val gson = Gson()
                    val earthquakeData = gson.fromJson(responseBody, EarthquakeData::class.java)
                    return earthquakeData
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return null
        }
    }
}