package com.sinognss.gnss.demo

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import com.sinognss.gnss.IGnssDataListener
import com.sinognss.gnss.IGnssDataManager

/**
 * @author: zhangchao
 * @date: 2026/7/1
 * @description:
 */
class GnssAidlClient(
    private val context: Context
) {

    private var gnssDataManager: IGnssDataManager? = null
    private var isBound = false

    var onLocation: ((GnssDataBean) -> Unit)? = null
    var onNmea: ((String) -> Unit)? = null

    private val aidlListener = object : IGnssDataListener.Stub() {

        /**
         * 接收全套测绘定位数据
         */
        override fun onGnssDataReceive(data: Bundle?) {
            data ?: return

            val bean = GnssDataBean.parse(data)

            // 大地坐标
            val lat = bean.lat
            val lon = bean.lon

            // 高程信息
            val altAntenna = bean.alt      // 地面高程，已叠加天线高
            val altRaw = bean.oAlt         // GNSS 板卡原始相位中心高程

            // 局部平面坐标
            val n = bean.n
            val e = bean.e
            val z = bean.z

            // 解算状态
            val diffType = bean.diffType
            val trackSat = bean.trackSatNum
            val solutionSat = bean.solutionSatNum
            val diffDelay = bean.diffDelay
            val utcTime = bean.utcTime

            Log.d(
                "GNSS_AIDL_DATA",
                "lat=$lat, lon=$lon, alt=$altAntenna, rawAlt=$altRaw, n=$n, e=$e, z=$z, diffType=$diffType, trackSat=$trackSat, solutionSat=$solutionSat, diffDelay=$diffDelay, utcTime=$utcTime"
            )

            onLocation?.invoke(bean)
        }

        /**
         * 接收完整原始 NMEA 报文
         */
        override fun onNmeaReceive(nmea: String?) {
            if (nmea.isNullOrBlank()) return
            onNmea?.invoke(nmea)
            Log.d("GNSS_AIDL_NMEA", nmea)
        }
    }

    private val serviceConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            gnssDataManager = IGnssDataManager.Stub.asInterface(service)

            try {
                gnssDataManager?.registerGnssDataListener(aidlListener)
                Log.d("GNSS_AIDL", "AIDL service connected and listener registered")
            } catch (e: RemoteException) {
                Log.e("GNSS_AIDL", "registerGnssDataListener failed", e)
            }
        }

        override fun onServiceDisconnected(name: ComponentName) {
            gnssDataManager = null
            isBound = false
            Log.w("GNSS_AIDL", "AIDL service disconnected")
        }

        override fun onBindingDied(name: ComponentName) {
            gnssDataManager = null
            isBound = false
            Log.w("GNSS_AIDL", "AIDL binding died")
        }

        override fun onNullBinding(name: ComponentName) {
            gnssDataManager = null
            isBound = false
            Log.w("GNSS_AIDL", "AIDL null binding")
        }
    }


    /**
     * 绑定 GNSS TOOL AIDL 服务
     */
    fun bindAidlService() {
        val intent = Intent().apply {
            component = ComponentName(
                "com.sinognss.gnsstool",
                "com.sinognss.sm.mock.service.GnssMockAidlService"
            )
        }
        // 绑定远程服务
        isBound = context.bindService(intent, serviceConnection!!, Context.BIND_AUTO_CREATE)

        Log.d("GNSS_AIDL", "bindService result=$isBound")
    }

    /**
     * 注销监听并解绑服务
     */
    fun unbindAidlService() {
        try {
            gnssDataManager?.unregisterGnssDataListener(aidlListener)
        } catch (e: RemoteException) {
            Log.e("GNSS_AIDL", "unregisterGnssDataListener failed", e)
        }

        if (isBound) {
            context.unbindService(serviceConnection)
            isBound = false
        }

        gnssDataManager = null
    }
}
