package es.verdnatura.presentation.view.feature.smarttag.sacador.fragment

import android.content.Context
import android.util.Log
import android.view.View
import android.view.View.*
import android.view.inputmethod.EditorInfo
import androidx.activity.OnBackPressedCallback
import androidx.core.os.bundleOf
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorAssociatesmarttagBinding
import es.verdnatura.databinding.FragmentSacadorAssociatesmarttagBindingImpl
import es.verdnatura.databinding.FragmentVehiclecontrolBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInput
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogThreeButtons
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.smarttag.adapter.SmartTagAdapter
import es.verdnatura.presentation.view.feature.smarttag.model.SmartTag
import timber.log.Timber

class AssociateSmartTagsFragment(
    var entryPoint: String = ""
) : BaseFragment<FragmentSacadorAssociatesmarttagBinding, SmartTagsViewModel>(
    SmartTagsViewModel::class
) {


    private var goBack: Boolean = false
    override fun getLayoutId(): Int = R.layout.fragment_sacador_associatesmarttag
    private lateinit var customDialog: CustomDialog
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogInput: CustomDialogInput
    private lateinit var customDialogThreeButtons: CustomDialogThreeButtons
    private var listSmartTags: ArrayList<SmartTag> = ArrayList()
    private var smartAdapter: SmartTagAdapter? = null
    private var itemScaned: String = ""

    companion object {
        fun newInstance(entryPoint: String) = AssociateSmartTagsFragment(entryPoint)
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
       // Timber.i("VERDNATURA:attached")
        val callback: OnBackPressedCallback =
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                    // Leave empty do disable back press or
                    // write your code which you want
                    //Log.i("VERDNATURA:", "PULSADO")

                }
            }
        requireActivity().onBackPressedDispatcher.addCallback(
            this,
            callback
        )

        //if (context is OnCollectionSelectedListener) onCollectionSelectedListener = context
    }

    override fun init() {

        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogInput = CustomDialogInput(requireContext())
        customDialogThreeButtons = CustomDialogThreeButtons(requireContext())
        goBack = false
         ma.hideBottomNavigation(View.GONE)
        binding.splashProgress.visibility = GONE

        setEvents()
        setToolBar()

        showScanSmartTags()
        super.init()
    }

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

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = getString(R.string.smarttagAssociate)

    }

    private fun bindShelving_add(shelvingOrSmarttag: String) {

        binding.splashProgress.visibility = VISIBLE
        //poner el bindshelving aqui

        viewModel.workerShelving_add(getData(USER),
            getData(PASSWORD), shelvingOrSmarttag)

        itemScaned = shelvingOrSmarttag

    }

    private fun bindShelving_remove() {

        // binding.splashProgress.visibility = VISIBLE
        //ponser el unbindshleving aqui
        //sergio:esto se debe hacer en

        viewModel.workerShelving_delete(getData(USER),
            getData(PASSWORD), listSmartTags.last().code.toString())

       /* ("http://localhost:7777/unbindShelving/${listSmartTags.first().code}" + "&" + listSmartTags.last().code + "&${listSmartTags.size}").toast(
            requireContext()
        )*/

    }

    private fun scanRequest() {
        binding.scanInput.requestFocus()
        hideKeyboards()
    }

    private fun hideKeyboards() {
        try {
            requireActivity().hideKeyboard()
        } catch (e: Exception) {
        }
    }

    private fun setEvents() {

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

    }

    override fun observeViewModel() {

        with(viewModel) {
            binding.splashProgress.visibility = GONE
            responseadd.observe(viewLifecycleOwner, Observer {
               // Log.i("VERDNATURA::", "Revisar llamada de las etiquetas smarttags : ${it.response}")

                if (it.isError) {
                    ma.messageWithSound(getString(R.string.shelvingSure)+it.errorMessage,true,false)

                } else {

                    ma.messageWithSound(getString(R.string.insertedLabel),false,false)
                        var nameSmartTagwithWagon =
                            getTextScaned(0) + itemScaned
                        customDialogList.setTitle(getTextToPosition(0))

                            listSmartTags.add(SmartTag(itemScaned, nameSmartTagwithWagon))
                            smartAdapter!!.notifyDataSetChanged()

                        customDialogList.setValue("")


                }
                binding.splashProgress.visibility = GONE
            })
            responseremove.observe(viewLifecycleOwner, Observer {

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage,true,false)
                    /*customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()*/
                } else {


                    listSmartTags.removeAt(listSmartTags.size - 1)
                    smartAdapter!!.notifyDataSetChanged()

                    customDialogList.setValue("")
                    ma.messageWithSound(getString(R.string.deletedLabel),false,false)
                }
                binding.splashProgress.visibility = GONE
            })
        }

    }

    private fun getTextToPosition(TagsScaned: Int): String {


        return when (TagsScaned) {
            0 -> getString(R.string.scanSmarttagOrShelving)
            1 ->  getString(R.string.scanHighLabel)
            2 ->  getString(R.string.scanMedLabel)
            3 ->  getString(R.string.scanLowLabel)
            4 -> getString(R.string.scannedWagon)
            else -> {""}
        }

    }

    private fun getTextScaned(TagScaned: Int): String {


        return when (TagScaned) {
            0 ->  getString(R.string.scanned)
            1 ->  getString(R.string.wagoon)
            2 -> getString(R.string.scanHighLabel)
            3 -> getString(R.string.scanMedLabel)
            4 -> getString(R.string.scanLowLabel)
            else -> {""}
        }



    }

    private fun showScanSmartTags() {

        customDialogList.setTitle(getString(R.string.scanSmarttagOrShelving))
            .setOkButton(getString(R.string.end)) {

                ma.hideKeyboard(customDialogList.getEditText())

                if (listSmartTags.size > 0) {
                    //  setFragmentResult("requestkey", bundleOf("tagMode" to "SmartTag"))
                    customDialogList.dismiss()
                        val result = getString(R.string.complete)
                        setFragmentResult("requestKey", bundleOf("tagMode" to result))
                       ma.openFragmentPickers(true)
                    /*listSmartTags.forEach {
                        Log.i("VERDNATURA:","El codigo es :${it.code}")
                        }
                      workerShelving_add(userFk, it.code!!)*/

                } else {
                  /*  customDialog.setTitle("Atención").setDescription("No ha escaneado Smartags")
                        .setOkButton("Ok")
                        {*/
                            customDialogList.dismiss()
                            requireActivity().onBackPressed()

                       // }.show()
                }

            }.setKoButton(getString(R.string.undone)) {
                ma.hideKeyboard(customDialogList.getEditText())

                if (!listSmartTags.isEmpty()) {

                    bindShelving_remove()

                } else {
                    customDialogList.dismiss()
                    requireActivity().onBackPressed()

                }

                //
            }.setValue("").show()

        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5 || actionId == 6) {
                if (!customDialogList.getValue().isNullOrEmpty()) {
                    bindShelving_add(customDialogList.getValue().uppercase())
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }


        smartAdapter = SmartTagAdapter(listSmartTags, object : OnSmartTagRowClickListener {
            override fun OnSmartTagRowClickListener(item: SmartTag) {
            }
        }, showDelete = false)
        customDialogList.getRecyclerView().adapter = smartAdapter
        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

    }

}

