/*
    Предрейсовые осмотры - мобильное приложение
    Нативный модуль встроенного сканера: доставка штрихкода в JS через событие по мосту.
*/

package com.parus_pre_trip_inspections

import android.view.View
import android.view.ViewGroup
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
import com.facebook.react.bridge.ReactMethod
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.facebook.react.bridge.Arguments

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

    init {
        sharedReactContext = reactApplicationContext
    }

    companion object {
        private const val MODULE_NAME = "HardwareScannerModule"
        private const val LOG_TAG = "PTI_HwScan"
        const val EVENT_HARDWARE_SCANNER_DATA = "HardwareScannerData"
        private const val EVENT_HARDWARE_SCANNER_TRIGGER = "HardwareScannerTriggerPressed"
        private const val TRIGGER_DEBOUNCE_MS = 600L

        @Volatile
        var sharedReactContext: ReactApplicationContext? = null
            private set

        @Volatile
        private var lastTriggerEmitTime = 0L

        fun emitBarcodeToJs(barcode: String?) {
            if (barcode.isNullOrEmpty()) return
            val ctx = sharedReactContext ?: return
            val payload = barcode
            try {
                if (!ctx.hasActiveCatalystInstance()) return
                ctx.runOnUiQueueThread {
                    try {
                        if (!ctx.hasActiveCatalystInstance()) return@runOnUiQueueThread
                        val map = Arguments.createMap()
                        map.putString("barcode", payload)
                        ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                            ?.emit(EVENT_HARDWARE_SCANNER_DATA, map)
                    } catch (_: Exception) {}
                }
            } catch (_: Exception) {}
        }

        //Эмит триггера только с UiQueueThread
        fun emitTriggerFromActivity(appContext: android.content.Context?): Boolean {
            val now = System.currentTimeMillis()
            if (now - lastTriggerEmitTime < TRIGGER_DEBOUNCE_MS) return false
            lastTriggerEmitTime = now
            val ctx = sharedReactContext ?: return true
            try {
                if (!ctx.hasActiveCatalystInstance()) return true
                ctx.runOnUiQueueThread {
                    try {
                        if (!ctx.hasActiveCatalystInstance()) return@runOnUiQueueThread
                        ctx.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
                            ?.emit(EVENT_HARDWARE_SCANNER_TRIGGER, null)
                    } catch (_: Exception) {}
                }
            } catch (_: Exception) {}
            return true
        }
    }

    override fun getName(): String = MODULE_NAME

    @ReactMethod
    fun setCameraViewsNotFocusable() {
        try {
            val activity = reactApplicationContext.currentActivity ?: return
            val content = activity.window?.decorView?.findViewById<View>(android.R.id.content) ?: return
            setNotFocusableRecursive(content)
        } catch (_: Exception) {}
    }

    private fun setNotFocusableRecursive(view: View) {
        val name = view.javaClass.simpleName
        if (name.contains("Camera", ignoreCase = true) ||
            name.contains("Preview", ignoreCase = true) ||
            name.contains("TextureView", ignoreCase = true) ||
            name.contains("SurfaceView", ignoreCase = true)
        ) {
            view.setFocusable(false)
            view.setFocusableInTouchMode(false)
        }
        if (view is ViewGroup) {
            for (i in 0 until view.childCount) {
                setNotFocusableRecursive(view.getChildAt(i))
            }
        }
    }
}
