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

import android.content.Context
import android.view.View.VISIBLE
import android.view.inputmethod.EditorInfo
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.common.itemScanValue
import es.verdnatura.presentation.view.component.CustomDialog
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, CollectionViewModel>(CollectionViewModel::class) {

    private var goBack: Boolean = false
    private var onCollectionSelectedListener: OnCollectionSelectedListener? = 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.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 {
            ma.onMyBackPressed()
        }

        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.scanInput.setText(textScanned_filterDouble(binding.scanInput.text!!.toString()))
                    try {
                        binding.scanInput.setText(
                            itemScanValue(
                                binding.scanInput.text.toString(),
                                arrayOf("ticket", "saleGroup"),
                                "id"
                            ).toString().toInt().toString(),
                        )
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            message = ex.message.toString(),
                            isError = true,
                            isPlayed = true
                        )
                    }
                    //Tarea 6458 descomentar si ok

                    try {
                        viewModel.ticketState(
                            itemScanValue(
                                binding.scanInput.text.toString(),
                                arrayOf("ticket", "saleGroup"),
                                "id"
                            ).toString().toInt()
                        )
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            getString(R.string.errorInput),
                            isPlayed = true,
                            isError = true
                        )
                    }
                }

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

    override fun observeViewModel() {
        with(viewModel) {
            collectionTicketList.observe(viewLifecycleOwner) {
                binding.scanInput.setText("")
                if (!goBack) navigateToCollectionList(it)
                goBack = false

            }
            responseTicketState.observe(
                    viewLifecycleOwner
            ) {
                if ((it.code == "ON_CHECKING" || it.code == "CHECKED") && it.user.id != mobileApplication.userId) {
                    val 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()

                            try {
                                viewModel.getSales(
                                    collectionFk = itemScanValue(
                                        binding.scanInput.text.toString(),
                                        arrayOf("ticket", "saleGroup"),
                                        "id"
                                    ).toString().toInt(),
                                    print = "0",
                                    source = ConstAndValues.ON_CHECKING
                                )

                            } catch (ex: Exception) {
                                ma.messageWithSound(
                                    message = getString(R.string.errorScanItem),
                                    isError = true,
                                    isToasted = true,
                                    isPlayed = true
                                )
                            }

                        }.setKoButton(getString(R.string.cancel)) {
                            binding.scanInput.setText("")
                            binding.scanInput.requestFocus()
                            customDialogWarning.dismiss()
                        }.show()
                    customDialogWarning.currentFocus
                } else {
                    viewModel.getSales(
                        collectionFk = itemScanValue(
                            binding.scanInput.text.toString(),
                            arrayOf("ticket", "saleGRoup"),
                            "id"
                        ).toString().toInt(),
                        print = "0",
                        source = ConstAndValues.ON_CHECKING
                    )

                }
            }
        }

    }

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

}
