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

import android.media.MediaPlayer
import android.view.View.GONE
import android.view.inputmethod.EditorInfo
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.OnSmartTagRowClickListener
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.buffer.fragment.adapter.BufferAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
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: BufferAdapter? = null
    private var itemScaned: Int = 0
    var mperror: MediaPlayer? = null

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

    override fun init() {

        customDialogList = CustomDialogList(requireContext())
        goBack = false
        ma.hideBottomNavigation(GONE)
        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)
        setEvents()
        setToolBar()
        showExpeditionOrBufferScan()
        super.init()
    }

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

    private fun setToolBar() {

        binding.mainToolbar.toolbarTitle.text = entryPoint

    }

    private fun checkLoadExpedition(expeditionOrBuffer: Int) {

        listTags.add(
            SmartTag(
                expeditionOrBuffer.toString(),
                getTextScaned(listTags.size + 1) + " $expeditionOrBuffer"
            )
        )
        customDialogList.setTitle(getString(R.string.scanBuffer))
        tagsAdapter!!.notifyItemInserted(listTags.size - 1)

        if (listTags.size == 2) {
            viewModel.expeditionLoadingAdd(
                vBufferFk = expeditionOrBuffer,
                vExpeditionFk = listTags.first().code.toString().toInt()
            )

        }
        itemScaned = expeditionOrBuffer
    }

    private fun setEvents() {

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

        }

    }

    override fun observeViewModel() {

        with(viewModel) {
            bufferLoadResponse.observe(viewLifecycleOwner) {

                ma.messageWithSound(
                    it,
                    isError = it != getString(R.string.registerAdded),
                    isPlayed = true,
                    isToasted = true
                )

                listTags.clear()
                tagsAdapter!!.notifyItemRangeRemoved(
                    0, 2
                )
                customDialogList.dismiss()
                showExpeditionOrBufferScan()

            }

        }

    }

    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()
                ma.onMyBackPressed()

            }.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) {
                if (customDialogList.getValue().isNotEmpty()) {
                    try {
                        checkLoadExpedition(customDialogList.getValue().toInt())
                    } catch (ex: Exception) {
                        ex.message!!.toast(requireContext())
                    }
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }


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

    }

}



