package com.joe.camera.webcam

import android.Manifest
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import android.view.WindowManager
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import com.joe.camera.webcam.ui.WebCamApp

class MainActivity : ComponentActivity() {
    private val viewModel: MainViewModel by viewModels()
    private var backgroundExitRequested = false
    private val permissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        if (permissions[Manifest.permission.CAMERA] == true) viewModel.startBle()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        requestPermissions()
        setContent { WebCamApp(viewModel) }
    }

    private fun requestPermissions() {
        val permissions = buildList {
            add(Manifest.permission.CAMERA)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                add(Manifest.permission.BLUETOOTH_SCAN); add(Manifest.permission.BLUETOOTH_CONNECT); add(Manifest.permission.BLUETOOTH_ADVERTISE)
            } else { add(Manifest.permission.ACCESS_FINE_LOCATION) }
            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }
        permissionLauncher.launch(permissions.toTypedArray())
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean = when (keyCode) {
        KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN -> true
        else -> super.onKeyDown(keyCode, event)
    }
    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean = when (keyCode) {
        KeyEvent.KEYCODE_VOLUME_UP -> { viewModel.toggleRecording(); true }
        KeyEvent.KEYCODE_VOLUME_DOWN -> { viewModel.toggleBlackScreen(); true }
        else -> super.onKeyUp(keyCode, event)
    }
    override fun onStop() {
        super.onStop()
        if (!isChangingConfigurations && !isFinishing && !backgroundExitRequested) {
            backgroundExitRequested = true
            viewModel.exitAppWhenRecordingSaved {
                runOnUiThread {
                    finishAndRemoveTask()
                }
            }
        }
    }
}
