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

import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentAutomaticAddItemBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnAutomaticItemClickListener
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.feature.ubicador.adapter.AutomaticAdapter
import es.verdnatura.presentation.view.feature.ubicador.model.ItemEscanerVO
import java.lang.Boolean.TRUE


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class AutomaticAddItemFragment(
    var shelvingFk: String = "",
    var titleAction: String? = null
) : BaseFragment<FragmentAutomaticAddItemBinding, AutomaticAddItemViewModel>(
    AutomaticAddItemViewModel::class
) {

    private var adapter: AutomaticAdapter? = null
    private var listItems: ArrayList<ItemEscanerVO> = ArrayList()
    private var deep: Int = 1
    private var contador = 0

    companion object {
        fun newInstance(entryPoint: String, titleAction: String) =
            AutomaticAddItemFragment(entryPoint, titleAction)
    }

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

    override fun init() {
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text = titleAction
        setEvents()
        setViews()
        setToolBar()
        super.init()
    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarSubtitle.visibility = View.VISIBLE
    }

    private fun setSubtitle() {
        binding.mainToolbar.toolbarSubtitle.text = getString(R.string.labels) + contador
    }

    private fun setViews() {
        adapter = AutomaticAdapter(listItems, object : OnAutomaticItemClickListener {
            override fun onAutomaticItemClickListener(position: Int) {
                contador -= 1
                setSubtitle()
                if (listItems.size > position) {
                    listItems.removeAt(position)
                }

                adapter!!.notifyDataSetChanged()
            }
        })
        binding.itemsRecyclerview.adapter = adapter
        binding.itemsRecyclerview.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
    }

    private fun setEvents() {
        binding.editMatricula.requestFocus()
        binding.editMatricula.setOnEditorActionListener { v, actionId, event ->

            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!binding.editMatricula.text.toString().isNullOrEmpty()) {
                    contador += 1
                    setSubtitle()
                  //  binding.editMatricula.setText(textScanned_filterDouble(binding.editMatricula.text.toString()))
                    try {
                       listItems.add(
                            0, ItemEscanerVO(
                                itemScanValue(
                                    textScanned_filterDouble(binding.editMatricula.text.toString()),
                                    "buy",
                                    "more"
                                ).toString().toLong()
                            )
                        )
                        adapter!!.notifyDataSetChanged()
                    } catch (ex: Exception) {
                        ma.messageWithSound(ex.message.toString(), true, true)
                    }
                }
                binding.editMatricula.setText("")
                ma.hideKeyboard(binding.editMatricula)
                return@setOnEditorActionListener true
            }

            return@setOnEditorActionListener false
        }

        binding.buttonFinalizar.setOnClickListener {
            val listString: ArrayList<Long> = ArrayList()
            val listInt: ArrayList<Long> = ArrayList()
            listItems.forEach {
                listString.add(it.item)
                listInt.add(it.item)
            }
            binding.splashProgress.visibility = View.VISIBLE

            if (binding.mainToolbar.toolbarTitle.text.equals(getString(R.string.titleChecker))) {

                viewModel.itemShelving_addList(
                    shelvingFk,
                    "" + listInt + "",
                    TRUE,
                    getDataInt(WAREHOUSEFK)
                )
            } else {
                /* viewModel.itemShelving_addList(
                     shelvingFk,
                     "" + listInt + "",
                     FALSE,
                     getDataInt(WAREHOUSEFK))*/
                viewModel.itemShelvingMake_multi(
                    shelvingFk,
                    listString,
                    getDataInt(WAREHOUSEFK)
                )
            }
        }

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

    override fun observeViewModel() {
        with(viewModel) {
            response.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)
                } else {
                    requireActivity().onBackPressed()
                }
            })
        }
    }

}
