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

import android.view.View
import android.view.inputmethod.EditorInfo
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionscanSorterBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.ItemScanned
import es.verdnatura.presentation.view.component.CustomDialogInputTwoValues
import org.json.JSONObject

class CmrExpeditionPalletFragment(
    var title: String = ""
) : BaseFragment<FragmentExpeditionscanSorterBinding, CmrExpeditionPalletViewModel>(
    CmrExpeditionPalletViewModel::class
) {

    override fun getLayoutId(): Int = R.layout.fragment_expeditionscan_sorter
    private lateinit var customDialogList: CustomDialogInputTwoValues
    private var itemScaned: String = ""
    private var dataScanned: ItemScanned? = null
    private var dataScannedTwo: ItemScanned? = null

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

    override fun init() {

        customDialogList = CustomDialogInputTwoValues(requireContext())
        ma.hideBottomNavigation(View.GONE)
        setEvents()
        setToolBar()
        showExpeditionPalletScan()
        super.init()
    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarTitle.text = title
    }

    private fun cmrExpeditionPalletAdd(vExpeditionPallet: Int?, vCmrId: Int?) {

        viewModel.cmrExpeditionPalletAdd(
            vExpeditionPallet!!, vCmrId!!
        )
        customDialogList.dismiss()
        showExpeditionPalletScan()

    }

    private fun setEvents() {

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

        }

    }

    private fun showExpeditionPalletScan() {
        customDialogList.setHint(true)
        customDialogList.setValue("")
        customDialogList.setValueTwo("")
        customDialogList.setInfoTex(getString(R.string.codeQrORPallet))
        customDialogList.setInfoTextTwo(getString(R.string.codeQrOrCMR))
        customDialogList.setTitle(getString(R.string.scanValues))
        customDialogList.setHint(false)

        customDialogList.setOkButton(getString(R.string.end)) {
            ma.hideKeyboard(customDialogList.getEditText())
            customDialogList.dismiss()
            binding.mainToolbar.backButton.performClick()
        }.setValue("").show()

        customDialogList.setFocusText()
        ma.hideKeyboard(customDialogList.getEditText())
        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (customDialogList.getValue().isNotEmpty()) {
                    dataScanned = itemScan(customDialogList.getValue())

                    if (dataScanned != null) {

                        customDialogList.setValue(dataScanned!!.id.toString())
                        customDialogList.setHint(true)
                        if (dataScanned!!.table == "cmr") {
                            customDialogList.setInfoTextTwo(getString(R.string.scanLabelPallet))
                        } else {
                            customDialogList.setInfoTextTwo(getString(R.string.scanLabelCMR))
                        }
                        customDialogList.setHint(false)
                    }
                }

                return@setOnEditorActionListener false

            }
            false

        }
        customDialogList.getEditTextTwo().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (customDialogList.getValueTwo().isNotEmpty() && customDialogList.getValue()
                        .isNotEmpty()
                ) {
                    dataScannedTwo = itemScan(customDialogList.getValueTwo())
                    if (dataScannedTwo == null) {
                        cmrExpeditionPalletAdd(
                            customDialogList.getValue().toInt(),
                            customDialogList.getValueTwo().toInt()
                        )

                    } else {
                        if (dataScanned != null) {

                            if (dataScanned!!.table == dataScannedTwo!!.table) {
                                ma.messageWithSound(
                                    getString(R.string.errorSameType),
                                    isError = true,
                                    isPlayed = true,
                                    titleWithError = getString(R.string.info),
                                    isToasted = true
                                )
                                customDialogList.setValueTwo("")
                            } else {
                                customDialogList.setValueTwo(dataScanned!!.id.toString())
                                cmrExpeditionPalletAdd(
                                    if (dataScannedTwo!!.table == "cmr") {
                                        dataScanned!!.id
                                    } else {
                                        dataScannedTwo!!.id
                                    }, if (dataScannedTwo!!.table == "cmr") {
                                        dataScannedTwo!!.id
                                    } else {
                                        dataScanned!!.id
                                    }
                                )
                            }
                        } else {
                            cmrExpeditionPalletAdd(
                                customDialogList.getValue().toInt(), dataScannedTwo!!.id

                            )
                        }
                    }
                }
            }

            return@setOnEditorActionListener true
        }

    }

}

private fun itemScan(value: String): ItemScanned? {

    return try {
        val valueScanned = ItemScanned(JSONObject(value))

        if (valueScanned.table == "cmr" || valueScanned.table == "expeditionPallet") {
            valueScanned
        } else {
            null
        }

    } catch (ex: Exception) {
        return null
    }

}
