package com.humand.demo.modules.Torch

import android.content.Context
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import com.facebook.react.bridge.Promise
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod

class TorchModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {

    private var isOn: Boolean = false
    private val cameraManager: CameraManager = reactContext.getSystemService(Context.CAMERA_SERVICE) as CameraManager
    private val cameraId: String = cameraManager.cameraIdList.firstOrNull { id ->
        val characteristics = cameraManager.getCameraCharacteristics(id)
        characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
    } ?: ""

    override fun getName(): String {
        return "Torch"
    }

    @ReactMethod
    fun toggleTorch(newState: Boolean, promise: Promise) {
        try {
            if (cameraId.isNotEmpty()) {
                cameraManager.setTorchMode(cameraId, newState)
                isOn = newState
                promise.resolve(true)
            } else {
                promise.reject("Error", "No available camera with a flash found.")
            }
        } catch (e: CameraAccessException) {
            promise.reject("Error", e.message)
        }
    }

    @ReactMethod
    fun torchOn(promise: Promise) {
        promise.resolve(isOn)
    }
}
