package com.humand.demo.modules.HMTextInput

import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.common.MapBuilder
import com.facebook.react.module.annotations.ReactModule
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.annotations.ReactProp
import com.facebook.react.uimanager.events.RCTEventEmitter
import com.facebook.react.views.textinput.ReactTextInputManager

@ReactModule(name = HMTextInputManager.REACT_CLASS)
class HMTextInputManager(private val appContext: ReactApplicationContext) : ReactTextInputManager() {
  override fun getName(): String = REACT_CLASS

  override fun createViewInstance(reactContext: ThemedReactContext): HMTextInputView {
    val view = HMTextInputView(reactContext)
    val inputType: Int = view.getInputType()
    view.setInputType(inputType and -131073)
    view.imeOptions = EditorInfo.IME_ACTION_DONE
    view.setLayoutParams(ViewGroup.LayoutParams(-2, -2))
    view.pasteListener = object : HMTextInputView.PasteListener {
      override fun onPasteImage() {
        val event = Arguments.createMap()
        reactContext.getJSModule(RCTEventEmitter::class.java)
          .receiveEvent(view.id, "topPasteImage", event)
      }
    }
    return view
  }

  @ReactProp(name = "pasteImageLabel")
  fun setPasteImageLabel(view: HMTextInputView, label: String?) {
    view.pasteImageLabel = label
  }

  override fun getExportedCustomDirectEventTypeConstants(): Map<String, Any> {
    val base = super.getExportedCustomDirectEventTypeConstants().toMutableMap()
    base["topPasteImage"] = MapBuilder.of("registrationName", "onPasteImage")
    return base
  }

  companion object {
    const val REACT_CLASS = "AndroidTextInput"
  }
}

