package bums.lunatic.launcher.helpers

import android.Manifest
import android.annotation.SuppressLint
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 androidx.core.app.ActivityCompat
import bums.lunatic.launcher.utils.BLog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import java.util.concurrent.TimeUnit


class BluetoothManager {

    enum class BLUETOOTH_STATE(val statestr: String) {
        ENABLED("enabledBlutooth"),
        DISABLED("disableBlutooth"),
        NOT_SUPPORT("notSupport")
    }

    lateinit var context: Context
    var blueToothAdapter:BluetoothAdapter? = null

    constructor(context: Context) {
        this.context = context
    }
    constructor() {

    }

//    init {
//        this.context = context
//    }

    fun initBluetoothAdapter(){
        if ( blueToothAdapter == null ){
            val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
            blueToothAdapter = bluetoothManager.getAdapter()
        }
    }

    fun register(){
        if (context == null) return
        context.registerReceiver(bluetoothreceiver, addFilterAction())
    }

    fun unregister(){
        if (context == null) return
        context.unregisterReceiver(bluetoothreceiver)
    }

    //페어링된 디바이스 정보 가져오기

    fun getPairedDevices() {
        val bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
        blueToothAdapter = bluetoothManager.adapter
        if (ActivityCompat.checkSelfPermission(context,Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
        var pairedDevices = blueToothAdapter?.bondedDevices
        if (pairedDevices?.size ?: 0 > 0) {
            pairedDevices?.forEach { i ->
                //bondState : 12 (페어링 등록된 상태)
                //bondState : 10 (페어링 등록 안됨)
                BLog.LOGE("getPairedDevices() / name : ${i.name}")
                BLog.LOGE("getPairedDevices() / bondState : ${i.bondState}")
                val isConnected = isConnected(i)
                if(PrefHelper.carName.length > 2 && i.name.equals(PrefHelper.carName) &&  isConnected != PrefHelper.isConnectedCar) {
                    PrefHelper.isConnectedCar = isConnected
                    sendToI(PrefHelper.isConnectedCar)
                }
            }
        }
    }


    fun sendToI(boolean: Boolean) {
        if (PrefHelper.telegramSendTarget.length > 5) {
            CoroutineScope(Dispatchers.IO).launch {
                val url =
                    "https://api.telegram.org/bot7934509464:AAE_xUbICxMdywLGnxo7BkeIqA1nVza4P9w/sendMessage?chat_id=${PrefHelper.telegramSendTarget}&text=${if(boolean) {
                        "돼지가 ${PrefHelper.carName}에 탔다요."
                    }else {
                        "${PrefHelper.carName}의 시동이 꺼졌다요."
                    }}"
                //7068729507
                // OkHttp 클라이언트 객체 생성
                val client = OkHttpClient.Builder()
                    .connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
                    .build()

                // GET 요청 객체 생성
                val builder: Request.Builder = Request.Builder().url(url)
                    .addHeader("Content-Type", "application/json").get()

                val request: Request = builder.build()

                BLog.LOGE("sendToI telegram before request ")
                // OkHttp 클라이언트로 GET 요청 객체 전송
                val response: Response = client.newCall(request).execute()
                if (response.isSuccessful()) {
                    // 응답 받아서 처리
                    val body: ResponseBody? = response.body()
                    if (body != null) {

                    }
                    BLog.LOGE("sendToI telegram response isSuccessful ${body}")
                } else BLog.LOGE("sendToI telegram Error Occurred")
            }
        }
    }
    @SuppressLint("MissingPermission")
    fun isConnected(device: BluetoothDevice): Boolean {
        try {
            val m = device.javaClass.getMethod("isConnected")
            val connected = m.invoke(device) as Boolean
            BLog.LOGE("D >> " + device.name  + "  || isConnected >>> " + (if (connected) "TRUE" else "FALSE"))
            return connected
        } catch (e: Exception) {
            throw IllegalStateException(e)
        }
    }

    //블루투스 상태(켜짐 / 꺼짐 / 지원 불가 기기)
    fun blueToothState(): String {
        if (blueToothAdapter != null) {
            if (blueToothAdapter!!.isEnabled) {
                return BLUETOOTH_STATE.ENABLED.statestr
            } else {
                return BLUETOOTH_STATE.DISABLED.statestr
            }
        }
        return BLUETOOTH_STATE.NOT_SUPPORT.statestr
    }

    //add Receive action
    private fun addFilterAction(): IntentFilter {
        val stateFilter = IntentFilter()
        stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED) //BluetoothAdapter.ACTION_STATE_CHANGED : 블루투스 상태변화 액션
        stateFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
        stateFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED) //연결 확인
        stateFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED) //연결 끊김 확인
        /*
        stateFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
        stateFilter.addAction(BluetoothDevice.ACTION_FOUND) //기기 검색됨
        stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED) //기기 검색 시작
        stateFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) //기기 검색 종료
        stateFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST)
        */
        return stateFilter
    }

    //BlueTooth Receiver
    private var bluetoothreceiver = object : BroadcastReceiver(){
        override fun onReceive(context: Context?, intent: Intent?) {
            var state = intent?.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)
            val action = intent!!.action
            if (context == null) return
            if (ActivityCompat.checkSelfPermission(context!!, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) return
            val device: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)!!
            getPairedDevices()
        }
    }
}