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


import android.media.MediaPlayer
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.FragmentBufferLoadexpeditionBinding
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialogList
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

class BufferLoadFragment(
    var entryPoint: String = ""
) : BaseFragment<FragmentBufferLoadexpeditionBinding, BufferFragmentViewModel>(
    BufferFragmentViewModel::class
) {

    private var goBack: Boolean = false
    override fun getLayoutId(): Int = R.layout.fragment_buffer_loadexpedition
    private lateinit var customDialogList: CustomDialogList
    private var listTags: ArrayList<SmartTag> = ArrayList()
    private var tagsAdapter: SmartTagAdapter? = null
    private var itemScaned: String = ""
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null


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

    override fun init() {

        customDialogList = CustomDialogList(requireContext())
        goBack = false
        ma.hideBottomNavigation(GONE)
        binding.splashProgress.visibility = GONE

        mperror = MediaPlayer.create((activity as MainActivity),R.raw.error)
        mpok=   MediaPlayer.create((activity as MainActivity),R.raw.ok)

        setEvents()
        setToolBar()

        showExpeditionOrBufferScan()
        super.init()
    }

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

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = entryPoint

    }


    private fun checkLoadExpedition(ExpeditionOrBuffer: String) {

        listTags.add(SmartTag(ExpeditionOrBuffer, getTextScaned(listTags.size + 1) + ExpeditionOrBuffer))
        customDialogList.setTitle(getTextToPosition(listTags.size + 1))

        tagsAdapter!!.notifyDataSetChanged()


        if (listTags.size==2) {
            binding.splashProgress.visibility = VISIBLE
            viewModel.expeditionLoading_add(
                usuario = getData(USER),
                password=getData(PASSWORD),
                vBufferFk = ExpeditionOrBuffer,
                vExpeditionFk = listTags.first().code.toString())

        }

        itemScaned = ExpeditionOrBuffer

    }


    private fun setEvents() {

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

    }


    override fun observeViewModel() {


        with(viewModel) {
            binding.splashProgress.visibility = GONE
            bufferloadresponse.observe(viewLifecycleOwner, Observer {


                if (it.isError) {
                    ma.messageWithSound(it.errorMessage,it.isError,true)
                } else {
                            // sergio: viene de la bbdd así
                    if (it.response.equals(getString(R.string.registerAdded))){

                        it.response?.let { it1 -> ma.messageWithSound(it1,false,true) }
                    }else{
                        mperror?.start()
                        it.response.toast(requireContext())
                    }
                    listTags.clear()
                    tagsAdapter!!.notifyDataSetChanged()
                    showExpeditionOrBufferScan()


                }
                binding.splashProgress.visibility = GONE
            })

        }

    }

    private fun getTextToPosition(TagsScaned: Int): String {

        return getString(R.string.scanBuffer)
       /* when (TagsScaned) {
            1 -> getString(R.string.scanBuffer)
            else -> {getString(R.string.scanBuffer)}
        }*/

    }

    private fun getTextScaned(TagScaned: Int): String {

       return  when (TagScaned) {
            1 -> getString(R.string.expedition)
            2 -> getString(R.string.buffer)
            else -> { ""}

        }


    }

    private fun showExpeditionOrBufferScan() {

        customDialogList.setTitle(getString(R.string.scanLabelExpedition))
            .setOkButton(getString(R.string.close)) {

                ma.hideKeyboard(customDialogList.getEditText())


                listTags.clear()
                    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()) {


                    checkLoadExpedition(customDialogList.getValue())

                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }


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


    }


}



