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.component.CustomDialog
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 ParkingSaleFragment : BaseFragment<FragmentParkingBinding,ParkingSaleViewModel>(ParkingSaleViewModel::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(SaleVO: Any?) = ParkingFragment("")
    }


    override fun init() {
        setEvents()
        binding.mainToolbar.toolbarTitle.text = getString(R.string.Parking)
        binding.splashProgress.visibility=View.GONE
        setList()
        customDialog = CustomDialog(requireContext())
        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){
                    mperror?.start()
                    ma.messageWithSound(it.errorMessage,true,false)
                   /* customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage).setOkButton(getString(R.string.close)){
                        customDialog.dismiss()
                    }.show()*/
                }else{
                    ma.messageWithSound(it.errorMessage,false,false, isToasted = true)
                    numParking -= 1
                    if (numParking <= 0) {
                        //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?) {

        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("[a-zA-Z ]+".toRegex())
    }


}
