package com.erwan.revwatch.obd

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.erwan.revwatch.model.DeviceItem

class DeviceScanner(private val context: Context) {

    fun getBondedBluetoothDevices(): List<DeviceItem> {
        if (Build.VERSION.SDK_INT >= 31) {
            val hasPerm = ContextCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_CONNECT
            ) == PackageManager.PERMISSION_GRANTED
            if (!hasPerm) return emptyList()
        }

        @Suppress("DEPRECATION")
        val adapter = BluetoothAdapter.getDefaultAdapter() ?: return emptyList()
        if (!adapter.isEnabled) return emptyList()

        return adapter.bondedDevices.map { device ->
            DeviceItem(
                name = device.name ?: "Inconnu",
                address = device.address,
                subtitle = device.address,
                isPaired = true
            )
        }
    }

    fun startBluetoothDiscovery(onFound: (DeviceItem) -> Unit): BroadcastReceiver? {
        if (Build.VERSION.SDK_INT >= 31) {
            val hasScan = ContextCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_SCAN
            ) == PackageManager.PERMISSION_GRANTED
            if (!hasScan) return null
        }

        @Suppress("DEPRECATION")
        val adapter = BluetoothAdapter.getDefaultAdapter() ?: return null
        if (!adapter.isEnabled) return null

        val receiver = object : BroadcastReceiver() {
            private val seen = mutableSetOf<String>()

            override fun onReceive(ctx: Context, intent: Intent) {
                if (intent.action != BluetoothDevice.ACTION_FOUND) return
                @Suppress("DEPRECATION")
                val device = intent.getParcelableExtra<BluetoothDevice>(
                    BluetoothDevice.EXTRA_DEVICE
                ) ?: return
                if (device.address in seen) return
                seen.add(device.address)

                @Suppress("DEPRECATION")
                onFound(
                    DeviceItem(
                        name = device.name ?: "Inconnu",
                        address = device.address,
                        subtitle = device.address,
                        isPaired = false
                    )
                )
            }
        }

        context.registerReceiver(receiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        adapter.startDiscovery()
        return receiver
    }

    fun stopBluetoothDiscovery(receiver: BroadcastReceiver?) {
        receiver ?: return
        try { context.unregisterReceiver(receiver) } catch (_: Exception) {}

        if (Build.VERSION.SDK_INT >= 31) {
            val hasScan = ContextCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_SCAN
            ) == PackageManager.PERMISSION_GRANTED
            if (!hasScan) return
        }
        @Suppress("DEPRECATION")
        BluetoothAdapter.getDefaultAdapter()?.cancelDiscovery()
    }
}
