package com.sinognss.gnss.demo

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.location.LocationManager
import android.location.OnNmeaMessageListener
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.sinognss.gnss.demo.databinding.ActivityGnssLocationBinding

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

    private lateinit var locationManager: LocationManager

    private lateinit var binding: ActivityGnssLocationBinding

    private val nmeaListener = OnNmeaMessageListener { message, timestamp ->
        // message 为系统转发的 NMEA 原始报文
        Log.d("GNSS_NMEA_RAW", "timestamp=$timestamp, message=$message")
        runOnUiThread {
            binding.tvNmea.text = "NMEA:${message}"
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityGnssLocationBinding.inflate(layoutInflater)
        binding.root
        setContentView(binding.root)
        locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager

        registerNmeaListener()
    }

    private fun registerNmeaListener() {
        if (
            ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                1002
            )
            return
        }

        locationManager.addNmeaListener(nmeaListener)
    }

    override fun onDestroy() {
        super.onDestroy()
        locationManager.removeNmeaListener(nmeaListener)
    }
}
