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

import android.content.Context
import android.view.View
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.Observer
import es.verdnatura.R
import es.verdnatura.databinding.FragmentGeneralBlackBinding
import es.verdnatura.domain.ConstAndValues
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnCollectionSelectedListener
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionViewModel
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ControladorFragment :
    BaseFragment<FragmentGeneralBlackBinding, ControladorViewModel>(ControladorViewModel::class) {

    private var goBack: Boolean = false
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
    private var collectionViewModel: CollectionViewModel? = null
    override fun getLayoutId(): Int = R.layout.fragment_general_black

    companion object {
        fun newInstance() = ControladorFragment()
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnCollectionSelectedListener) onCollectionSelectedListener = context
    }

    override fun init() {

        binding.splashProgress.visibility = View.GONE
        binding.scanInput.visibility = VISIBLE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.controlticket)
        setEvents()
        ma.hideBottomNavigation(VISIBLE)
        super.init()
    }

    override fun onPause() {
        goBack = true
        super.onPause()
    }

    private fun setEvents() {

        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                goBack = false
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    binding.splashProgress.visibility = VISIBLE
                    binding.scanInput.setText(textScanned_filterDouble(binding.scanInput.text!!.toString()))
                    //Tarea 6458 descomentar si ok
                    /*   collectionViewModel = CollectionViewModel(mobileApplication)
                        collectionViewModel!!.ticketState(binding.scanInput.text.toString().toInt())
                        collectionViewModel!!.responseTicketState.observe(
                            viewLifecycleOwner,
                            Observer { it ->
                                binding.splashProgress.visibility = View.GONE
                               if ((it.code == "ON_CHECKING" || it.code == "CHECKED") && it.user.id != mobileApplication.userId) {
                                     var customDialogWarning = CustomDialog(requireContext())
                                     customDialogWarning.setTitle(getString(R.string.info))
                                     customDialogWarning.setDescription(
                                         if (it.code == "ON_CHECKING") {
                                             getString(R.string.checkingByUser, it.user.username)
                                         } else {
                                             getString(R.string.checkedByUser, it.user.username)
                                         }
                                     )
                                         .setOkButton(getString(R.string.aware)) {
                                             customDialogWarning.dismiss()
                                             binding.splashProgress.visibility= VISIBLE
                                              viewModel.collectionTicketGet(
                                                  sectorFk = mobileApplication.dataStoreApp.readDataStoreKey(
                                                      ConstAndValues.SECTORFK
                                                  ),
                                                  collectionFk = binding.scanInput.text.toString().toInt(),
                                                  print = "0",
                                                  type = ConstAndValues.CONTROLADOR
                                              )
                                         }.show()
                                     customDialogWarning.currentFocus
                                 } else {*/
                            viewModel.collectionTicketGet(
                                sectorFk = mobileApplication.dataStoreApp.readDataStoreKey(
                                    ConstAndValues.SECTORFK
                                ),
                                collectionFk = binding.scanInput.text.toString().toInt(),
                                print = "0",
                                type = ConstAndValues.CONTROLADOR
                            )
                         //   }
                        //})

                }

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

    override fun observeViewModel() {
        with(viewModel) {
            collectionTicketList.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                binding.scanInput.setText("")
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, isError = true, isPlayed = false)
                } else {

                    if (!goBack) navigateToCollectionList(it)
                    goBack = false
                }

            })

        }

    }

    private fun navigateToCollectionList(collection: CollectionVO) {
        onCollectionSelectedListener?.onCollectionSelected(collection, ConstAndValues.CONTROLADOR)
    }

}
