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

import android.media.MediaPlayer
import android.os.Bundle
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentParkingBinding
import es.verdnatura.domain.isParking
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.common.itemScanValue
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.parking.adapter.ParkingAdapter

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ParkingFragment(var menuOrigin: String) :
    BaseFragment<FragmentParkingBinding, ParkingViewModel>(ParkingViewModel::class) {

    private var scanerList: ArrayList<BarcodeVO> = ArrayList()
    private var adapter: ParkingAdapter? = null
    private var numParking: Int = 0
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null

    override fun getLayoutId(): Int = R.layout.fragment_parking

    companion object {
        fun newInstance(menuOrigin: String) = ParkingFragment(menuOrigin = menuOrigin)
    }

    override fun init() {

        setEvents()
        binding.mainToolbar.toolbarTitle.text = getString(R.string.Parking)

        if (menuOrigin == getString(R.string.main)) {
            hideBackButton(binding.mainToolbar)
        }

        setList()

        super.init()
    }

    private fun setEvents() {
        binding.scanInput.requestFocus()
        binding.scanInput.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (!binding.scanInput.text.isNullOrEmpty()) {
                    try {

                        checkScan(
                            itemScanValue(
                                binding.scanInput.text.toString(),
                                arrayOf("ticket", "saleGroup"),
                                "id"
                            ).toString()
                        )

                    } catch (ex: Exception) {
                        ex.toast(requireContext())
                    }
                }
                binding.scanInput.setText("")
                requireActivity().hideKeyboard()
                return@setOnEditorActionListener true
            }
            false
        }

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

    override fun observeViewModel() {
        with(viewModel) {
            responseParking.observe(viewLifecycleOwner) {

                ma.messageWithSound(
                    message = getString(R.string.Aparcado),
                    isError = false,
                    isPlayed = false,
                    isToasted = true
                )
                numParking -= 1
                if (numParking <= 0) {
                    mpok?.start()
                    setList()

                }
            }

        }
    }

    private fun setList() {
        scanerList = ArrayList()
        adapter = ParkingAdapter(scanerList, object : OnBarcodeRowClickListener {
            override fun onBarcodeRowClickListener(item: BarcodeVO) {
                try {
                    val position = scanerList.indexOf(item)
                    if (position != -1) {
                        scanerList.removeAt(position)
                        adapter!!.notifyItemRangeChanged(position, scanerList.size - position + 1)
                    }
                } catch (ex: Exception) {
                    ex.message.toString().toast(requireContext())
                }

            }
        })
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

        binding.fragmentParkingScanList.adapter = adapter
        binding.fragmentParkingScanList.layoutManager = lm
    }

    private fun checkScan(txtScan: String) {
        var isParking = false
        if (txtScan.isParking()
        ) {
            isParking = true
        }

        if (isParking) {
            numParking = scanerList.size
            scanerList.forEach {
                viewModel.setParking(
                    parking = txtScan, scanItem = it.code!!
                )
            }
        } else {
            scanerList.add(BarcodeVO(code = txtScan))
            adapter?.notifyItemInserted(scanerList.size - 1)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        mperror = MediaPlayer.create((activity as MainActivity), R.raw.error)
        mpok = MediaPlayer.create((activity as MainActivity), R.raw.ok)
        super.onCreate(savedInstanceState)
    }

}
