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

import android.view.inputmethod.EditorInfo
import es.verdnatura.R
import es.verdnatura.databinding.FragmentBufferBinding
import es.verdnatura.domain.toLong
import es.verdnatura.presentation.base.BaseFragment

class BufferFragment(
    var entryPoint: String = ""
) : BaseFragment<FragmentBufferBinding, BufferFragmentViewModel>(BufferFragmentViewModel::class) {
    override fun getLayoutId(): Int = R.layout.fragment_buffer

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

    override fun init() {

        setToolbar()
        setEvents()
        super.init()
    }

    private fun setToolbar() {
        binding.mainToolbar.toolbarTitle.text = entryPoint
    }

    private fun setEvents() {

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

        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    try {
                        when (entryPoint) {
                            getString(R.string.titleBufferEmpty) -> entryPoint = "UNLOADING"
                            getString(R.string.titleBufferFill) -> entryPoint = "LOADING"
                            getString(R.string.titleBufferAccumulate) -> entryPoint = "ACCUMULATION"
                            getString(R.string.titleBufferOff) -> entryPoint = "DISABLED"
                            getString(R.string.titleBufferStrapping) -> entryPoint = "STRAPPING"
                        }

                        viewModel.bufferSetTypeByName(
                            binding.scanInput.toLong(),
                            entryPoint

                        )
                    } catch (ex: Exception) {
                        ma.messageWithSound(
                            getString(R.string.itemNotValid),
                            isToasted = true,
                            isError = true,
                            isPlayed = true
                        )
                    }

                }
                binding.scanInput.setText("")
                ma.hideKeyboard(binding.scanInput)
                return@setOnEditorActionListener true
            }
            false
        }
    }

    override fun observeViewModel() {

        with(viewModel) {
            itemBufferType.observe(viewLifecycleOwner) {
                if (itemBufferType.value == false) {
                    ma.messageWithSound(getString(R.string.errorInput), isError = true, isPlayed = true, isToasted = true)
                } else {
                    binding.mainToolbar.backButton.performClick()
                }

            }
        }

    }

}