package es.verdnatura.presentation.view.feature.ticket.fragment

import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.itemScanValue

class TicketAdvanceFragment(var title: String) :
    BaseFragment<FragmentGeneralBlackBinding, TicketViewModel>(
        TicketViewModel::class
    ) {

    override fun getLayoutId(): Int = R.layout.fragment_general_black

    companion object {
        fun newInstance(title: String) = TicketAdvanceFragment(title = title)
    }

    override fun init() {

        binding.scanInput.visibility = VISIBLE
        binding.scanInput.hint = getString(R.string.scanLabelTicket)
        binding.mainToolbar.toolbarTitle.text = title

        setEvents()
        super.init()
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            ma.onMyBackPressed()
        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    try {

                        viewModel.ticketAdvancePackaging(
                            itemScanValue(
                                binding.scanInput.text.toString(), arrayOf("ticket"), "id"
                            ).toString().toInt(),
                            mobileApplication.userId!!
                        )
                    } catch (ex: Exception) {
                        getString(R.string.ticketFormatError)
                    }

                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

}

