package com.erwan.revwatch.obd

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.erwan.revwatch.model.BridgeConfig
import com.erwan.revwatch.model.ConnectionMode

sealed class OpenTransportResult {
    data class Ready(val transport: ElmTransport) : OpenTransportResult()
    data class Error(val message: String) : OpenTransportResult()
}

object ConnectionFactory {

    fun openTransport(context: Context, config: BridgeConfig): OpenTransportResult {
        return when (config.connectionMode) {
            ConnectionMode.BLUETOOTH -> openBluetooth(context, config)
            ConnectionMode.TEST -> OpenTransportResult.Error("Mode simulation: pas de transport physique")
        }
    }

    @Suppress("DEPRECATION")
    private fun openBluetooth(context: Context, config: BridgeConfig): OpenTransportResult {
        if (Build.VERSION.SDK_INT >= 31) {
            val hasPerm = ContextCompat.checkSelfPermission(
                context, Manifest.permission.BLUETOOTH_CONNECT
            ) == PackageManager.PERMISSION_GRANTED
            if (!hasPerm) return OpenTransportResult.Error("Permission Bluetooth manquante")
        }

        val adapter = BluetoothAdapter.getDefaultAdapter()
            ?: return OpenTransportResult.Error("Bluetooth indisponible")

        if (!adapter.isEnabled) return OpenTransportResult.Error("Active le Bluetooth")

        val device = try {
            if (config.btMacAddress.isNotBlank()) {
                adapter.getRemoteDevice(config.btMacAddress.trim())
            } else {
                adapter.bondedDevices?.firstOrNull()
            }
        } catch (_: Exception) { null }
            ?: return OpenTransportResult.Error("Aucun adaptateur Bluetooth appaire")

        return try {
            val transport = OBDLinkLXTransport.connect(device, adapter)
            OpenTransportResult.Ready(transport)
        } catch (e: Exception) {
            OpenTransportResult.Error("Echec connexion Bluetooth: ${e.message}")
        }
    }
}
