package com.humand.demo.modules.VolumeButtonListener

import android.view.KeyEvent
import com.facebook.react.bridge.Arguments
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

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

    companion object {
        var isEnabled: Boolean = false
            private set
        private var moduleInstance: VolumeButtonListenerModule? = null

        fun handleKeyEvent(keyCode: Int, action: Int): Boolean {
            if (!isEnabled) return false
            if (action != KeyEvent.ACTION_DOWN) return true

            val direction = when (keyCode) {
                KeyEvent.KEYCODE_VOLUME_UP -> "up"
                KeyEvent.KEYCODE_VOLUME_DOWN -> "down"
                else -> return false
            }

            moduleInstance?.sendVolumeButtonEvent(direction)
            return true
        }
    }

    init {
        moduleInstance = this
    }

    override fun getName(): String = "VolumeButtonListener"

    @ReactMethod
    fun setEnabled(enabled: Boolean) {
        isEnabled = enabled
    }

    @ReactMethod
    fun addListener(eventName: String) {
        // Required for NativeEventEmitter
    }

    @ReactMethod
    fun removeListeners(count: Int) {
        // Required for NativeEventEmitter
    }

    private fun sendVolumeButtonEvent(direction: String) {
        val params = Arguments.createMap().apply {
            putString("direction", direction)
        }
        reactApplicationContext
            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
            .emit("onVolumeButtonPress", params)
    }
}
