package com.tfa.sensair

import android.app.Activity
import android.os.Bundle
import android.widget.TextView
import android.bluetooth.BluetoothAdapter
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult
import android.bluetooth.le.BluetoothLeScanner
import android.graphics.Color
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.os.Handler

class MainActivity : Activity() {

    private lateinit var bluetoothAdapter: BluetoothAdapter
    private lateinit var bluetoothLeScanner: BluetoothLeScanner
    private lateinit var ppmValue: TextView
    private val REQUEST_BLUETOOTH_PERMISSIONS = 1
    private val scanInterval = 5000L // 5 seconds
    private val handler = Handler()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        ppmValue = findViewById(R.id.ppm_value)

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner

        checkPermissions()
        startAutomaticScan()
    }

    private fun checkPermissions() {
        val permissions = arrayOf(
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.ACCESS_FINE_LOCATION
        )

        val missingPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(this, missingPermissions.toTypedArray(), REQUEST_BLUETOOTH_PERMISSIONS)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_BLUETOOTH_PERMISSIONS) {
            if (grantResults.isNotEmpty() && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
                startAutomaticScan()
            } else {
                ppmValue.text = "Permissions not granted"
            }
        }
    }

    private fun startAutomaticScan() {
        handler.post(object : Runnable {
            override fun run() {
                startBleScan()
                handler.postDelayed(this, scanInterval)
            }
        })
    }

    private fun startBleScan() {
        bluetoothLeScanner.startScan(leScanCallback)
    }

    private val leScanCallback: ScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            val deviceName = result.device.name
            val scanRecord = result.scanRecord?.bytes
            if (deviceName != null && deviceName == "sensairS8" && scanRecord != null) {
                parseAdvertisingData(scanRecord)
            }
        }
    }

    private fun parseAdvertisingData(scanRecord: ByteArray) {
        val eirType = 0x88.toByte()
        var index = 0
        while (index < scanRecord.size) {
            val length = scanRecord[index].toInt()
            if (length == 0) break
            val type = scanRecord[index + 1]
            if (type == eirType) {
                val value = (scanRecord[index + 3].toInt() and 0xFF) shl 8 or (scanRecord[index + 2].toInt() and 0xFF)
                displayPpmValue(value)
                break
            }
            index += length + 1
        }
    }

    private fun displayPpmValue(value: Int) {
        ppmValue.text = "$value PPM"
        ppmValue.setTextColor(
            when {
                value < 600 -> Color.GREEN
                value in 600..999 -> Color.parseColor("#FFA500") // Orange
                value in 1000..1999 -> Color.RED
                else -> Color.MAGENTA
            }
        )
    }
}