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.domain.ConstAndValues.WAREHOUSEFK
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.AutomaticAdapterTEST
import java.lang.Boolean.TRUE

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

    private var adapter: AutomaticAdapterTEST? = null
    private var listItems: ArrayList<Long> = ArrayList()
    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 = AutomaticAdapterTEST(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()
                    try {
                        listItems.add(
                            0,
                            itemScanValue(
                                textScanned_filterDouble(binding.editMatricula.text.toString()),
                                "buy",
                                "more"
                            ).toString().toLong()

                        )
                        adapter!!.notifyItemInserted(0)
                    } catch (ex: Exception) {
                        ma.messageWithSound(ex.message.toString(), true, true)
                    }
                }
                binding.editMatricula.setText("")
                ma.hideKeyboard(binding.editMatricula)
                return@setOnEditorActionListener true
            } else {
                ma.messageWithSound("ACTION ID DIFERENTE", true, true)

            }

            return@setOnEditorActionListener false
        }

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


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

                viewModel.itemShelvingAddList(
                    shelvingFk,
                    "" + listInt + "",
                    TRUE,
                    mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                )
            } else {
                binding.splashAnimation.visibility = View.VISIBLE
                viewModel.itemShelvingMakeMulti(
                    shelvingFk,
                    listString,
                    mobileApplication.dataStoreApp.readDataStoreKey(WAREHOUSEFK)
                )
            }
        }

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

    override fun observeViewModel() {
        with(viewModel) {
            binding.splashAnimation.visibility = View.INVISIBLE
            response.observe(viewLifecycleOwner, Observer {
                requireActivity().onBackPressed()
            })
        }
    }

}
