package com.sinognss.gnss.demo

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.sinognss.gnss.demo.databinding.ActivityGnssLocationBinding

/**
 * @author: zhangchao
 * @date: 2026/7/1
 * @description:
 */
class GnssBroadcastActivity : AppCompatActivity() {


    private lateinit var binding: ActivityGnssLocationBinding


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGnssLocationBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }

    private val gnssReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action != "com.sinognss.gnss.location.ACTION_GNSS_LOCATION") {
                return
            }

            val bundle = intent.extras ?: return
            val data = GnssDataBean.parse(bundle)

            val lat = data.lat
            val lon = data.lon
            val alt = data.alt

            val n = data.n
            val e = data.e
            val z = data.z

            val diffType = data.diffType
            val trackSatNum = data.trackSatNum
            val solutionSatNum = data.solutionSatNum

            Log.d(
                "GNSS_BROADCAST",
                "lat=$lat, lon=$lon, alt=$alt, n=$n, e=$e, z=$z, diffType=$diffType, trackSat=$trackSatNum, solutionSat=$solutionSatNum"
            )

            binding.tvLocation.setText(data.toString())
        }
    }

    override fun onStart() {
        super.onStart()
        registerGnssBroadcast()
    }

    override fun onStop() {
        super.onStop()
        unregisterGnssBroadcast()
    }

    private fun registerGnssBroadcast() {
        val filter = IntentFilter("com.sinognss.gnss.location.ACTION_GNSS_LOCATION")

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            registerReceiver(
                gnssReceiver,
                filter,
                Context.RECEIVER_EXPORTED
            )
        } else {
            registerReceiver(gnssReceiver, filter)
        }
    }

    private fun unregisterGnssBroadcast() {
        try {
            unregisterReceiver(gnssReceiver)
        } catch (e: IllegalArgumentException) {
            Log.w("GNSS_BROADCAST", "Receiver already unregistered")
        }
    }
}