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


import android.media.MediaPlayer
import android.os.Bundle
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.FragmentParkingBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.hideKeyboard
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
import org.koin.android.ext.android.bind

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

   // private lateinit var customDialog: CustomDialog
    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)}
        //sergio: después de las últimas actualizaciones se queda activo. Se cambia opción visibilidad.
        //viewModel.hideProgressLoading()
        binding.splashProgress.visibility=View.GONE
        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()) {
                    checkScan(binding.scanInput.text.toString())
                }
                binding.scanInput.setText("")
                requireActivity().hideKeyboard()
                return@setOnEditorActionListener true
            }
            false
        }

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

    override fun observeViewModel() {
        with(viewModel){
            response.observe(viewLifecycleOwner, Observer {
                if (it.isError){
                    ma.messageWithSound(it.errorMessage, isError = true,isPlayed = true)

                }else{
                    ma.messageWithSound(message=getString(R.string.Aparcado), isError = false,isPlayed = false, isToasted = true)
                    numParking -= 1
                    if (numParking <= 0) {
                      //  binding.splashProgress.visibility = View.GONE
                        //viewModel.hideProgressLoading()
                        mpok?.start()
                        setList()
                    }
                }
            })

            isLoading.observe(viewLifecycleOwner, Observer {
                if (it){
                    binding.splashProgress.visibility = View.VISIBLE
                }else{
                    binding.splashProgress.visibility = View.GONE
                    }

            })

            isLoadingProgress.observe(viewLifecycleOwner, {

                    binding.splashProgress.visibility = it

            })


        }
    }

    private fun setList(){
        scanerList = ArrayList()
        adapter = ParkingAdapter(scanerList,object: OnBarcodeRowClickListener{
            override fun onBarcodeRowClickListener(item: BarcodeVO) {
                scanerList.removeAt(scanerList.indexOf(item))
                adapter?.notifyDataSetChanged()
            }
        })
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

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

    private fun checkScan(txtScan:String){
        var isParking:Boolean = false
        if (txtScan.trim().length == 4 && isLetter(txtScan.substring(txtScan.length - 1)) || txtScan.contains("-")){
            isParking = true
        }

        if (isParking){
            numParking = scanerList.size
            scanerList.forEach {
               // binding.splashProgress.visibility = View.VSIIBLE
                viewModel.parking(
                    usuario = getData(USER),
                    password = getData(PASSWORD),
                    parking = txtScan,
                    scanItem = it.code!!
                )
            }
        }else{
            scanerList.add(BarcodeVO(code = txtScan))
            adapter?.notifyDataSetChanged()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
       // val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER,0)
        mperror = MediaPlayer.create((activity as MainActivity),R.raw.error)
        mpok = MediaPlayer.create((activity as MainActivity),R.raw.ok)
        super.onCreate(savedInstanceState)
    }

    @Throws(NumberFormatException::class)
    fun isLetter(text: String): Boolean {
        return text.matches(getString(R.string.regExp).toRegex())
    }


}
