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


import android.content.Context
import android.graphics.drawable.Drawable
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.FragmentExpeditionPalletBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnBarcodeRowClickListener
import es.verdnatura.presentation.common.OnComprobarPalletViewClickListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPalletClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.articulo.adapter.BarcodeAdapter
import es.verdnatura.presentation.view.feature.articulo.model.BarcodeVO
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import es.verdnatura.presentation.view.feature.paletizador.adapter.ExpeditionPalletAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletListVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemScanList
import java.text.SimpleDateFormat
import java.util.*

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionPalletFragment(
    var itemExpeditionTruckVO: ItemExpeditionTruckVO? = null
) : BaseFragment<FragmentExpeditionPalletBinding, ExpeditionPalletViewModel>(
    ExpeditionPalletViewModel::class
) {


    private var adapter: ExpeditionPalletAdapter? = null
    private var onPalletClickListener: OnPalletClickListener? = null
    private var onComprobarPalletViewClickListener: OnComprobarPalletViewClickListener? = null
    private lateinit var customDialogList: CustomDialogList
    private var listExpeditions: ArrayList<BarcodeVO> = ArrayList()
    private var expeditionAdapter: BarcodeAdapter? = null
    private lateinit var customDialog: CustomDialog
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null


    companion object {
        fun newInstance(item: ItemExpeditionTruckVO) =
            ExpeditionPalletFragment(item)
    }

    override fun onAttach(context: Context) {
        if (context is OnPalletClickListener) onPalletClickListener = context
        if (context is OnComprobarPalletViewClickListener) onComprobarPalletViewClickListener =
            context
        super.onAttach(context)
    }

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

    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)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        binding.splashProgress.visibility = View.VISIBLE
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text =
            getCURDATE(itemExpeditionTruckVO!!.ETD) + " " + if (itemExpeditionTruckVO!!.Destino.isNullOrBlank()) {
                itemExpeditionTruckVO!!.description

            }else{
                itemExpeditionTruckVO!!.Destino
            }
        setToolBar()
        setEvents()
        viewModel.expeditionPallet_List(
            getData(USER),
            getData(PASSWORD), itemExpeditionTruckVO!!.truckFk
        )

        super.init()
    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

    }

    private fun setToolBar() {
        val listIcons: ArrayList<Drawable> = ArrayList()
        val iconReload: Drawable =
            resources.getDrawable(R.drawable.ic_autorenew_black_24dp, resources.newTheme())
        val iconPlus: Drawable =
            resources.getDrawable(R.drawable.ic_add_black_24dp, resources.newTheme())
        listIcons.add(iconReload)
        listIcons.add(iconPlus)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapter(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {
                    if (item == iconReload) {
                        binding.splashProgress.visibility = View.VISIBLE
                        viewModel.expeditionPallet_List(
                            getData(USER),
                            getData(PASSWORD), itemExpeditionTruckVO!!.truckFk
                        )
                    } else if (item == iconPlus) {
                        expeditionScanAdd()
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun getCURDATE(date: String): String {
        val c = Calendar.getInstance()
        val df = SimpleDateFormat(getString(R.string.dateCompleteFormat))
        val df2 = SimpleDateFormat(getString(R.string.timeFormat))
        c.time = df.parse(date)!!
        return df2.format(c.time)
    }

    override fun observeViewModel() {
        with(viewModel) {
            loadExpeditionPalletList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull { printExpeditionList(it) }
            })

            loadScanList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull { showScanExpeditions(it) }
            })

            response.observe(viewLifecycleOwner, Observer {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

                }
            })


            responseCheckexpeditionScanPut.observe(viewLifecycleOwner, Observer {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

                } else {

                    if (it.response == "0") {

                        //"Rutas iguales ${it.response}".toast(requireActivity())
                        ////Log.i("VERDNATURA:","Rutas iguales")
                    }
                    if (it.response == "1") {
                        mperror?.start()
                        //   "Resultado llamada $it.response".toast(requireActivity())
                        ////Log.i("VERDNATURA:","Rutas distintas")

                    }
                }
            })

        }


    }

    private fun printExpeditionList(it: ItemPalletListVO) {
        binding.splashProgress.visibility = View.GONE
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = ExpeditionPalletAdapter(
            it.list,
            onPalletClickListener!!,
            onComprobarPalletViewClickListener!!,
            itemExpeditionTruckVO!!
        )
        binding.expeditionPalletRecyclerview.adapter = adapter
        binding.expeditionPalletRecyclerview.layoutManager = lm

    }

    private fun expeditionScanAdd() {
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.expeditionScanAdd(
            getData(USER),
            getData(PASSWORD), vPalletFk = "0", vTruckFk = itemExpeditionTruckVO!!.truckFk
        )
    }

    private fun showScanExpeditions(it: ItemScanList) {

        binding.splashProgress.visibility = View.GONE

        listExpeditions = ArrayList()

        it.list.forEach {
            if (it.expeditionFk != "0")
                listExpeditions.add(BarcodeVO(code = it.expeditionFk))
        }

        customDialogList.setTitle(getString(R.string.expeditionP) + binding.mainToolbar.toolbarTitle.text + ")")
            .setOkButton(
                getString(
                    R.string.test
                )
            ) {
                ma.hideKeyboard(customDialogList.getEditText())


                if (listExpeditions.size > 0) {
                    onComprobarPalletViewClickListener!!.onComprobarPalletViewClickListener(
                        itemExpeditionTruckVO!!,
                        ItemPalletVO(Pallet = it.list.get(0).palletFk)
                    )
                } else {
                    customDialog.setTitle(getString(R.string.info))
                        .setDescription(getString(R.string.expeditionsError))
                        .setOkButton(getString(R.string.accept)) {
                            customDialog.dismiss()
                        }.show()
                }

                customDialogList.dismiss()


            }.setKoButton(getString(R.string.close)) {
            ma.hideKeyboard(customDialogList.getEditText())
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.expeditionPallet_List(
                getData(USER),
                getData(PASSWORD), itemExpeditionTruckVO!!.truckFk
            )
            listExpeditions = ArrayList()
            customDialogList.dismiss()
        }.setValue("").show()

        customDialogList.getEditText().requestFocus()
        ma.hideKeyboard(customDialogList.getEditText())

        customDialogList.getEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {
                if (!customDialogList.getValue().isNullOrEmpty()) {
                    try {
                        // val numExpedition = customDialogList.getValue().toDouble()
                        if (customDialogList.getValue().length >= 7) {
                            listExpeditions.add(0, BarcodeVO(code = customDialogList.getValue()))
                            customDialogList.setDescription(getString(R.string.total) + listExpeditions.size)
                            viewModel.expeditionScanPut(
                                getData(USER),
                                getData(PASSWORD),
                                it.list.get(0).palletFk,
                                customDialogList.getValue()
                            )
                            ////Log.i("VERDNATURA:"," palletizando ${it.list.get(0).palletFk} expedi: ${customDialogList.getValue()}")
                            viewModel.checkRouteExpeditionScanPut(
                                getData(USER),
                                getData(PASSWORD),
                                it.list.get(0).palletFk,
                                customDialogList.getValue()
                            )
                        } else {
                            if (mperror != null) mperror!!.start()
                        }
                    } catch (e: Exception) {
                        if (mperror != null) mperror!!.start()
                    }


                    expeditionAdapter!!.notifyDataSetChanged()
                }
                customDialogList.setValue("")
                ma.hideKeyboard(customDialogList.getEditText())
                return@setOnEditorActionListener true
            }
            false
        }

        expeditionAdapter = BarcodeAdapter(listExpeditions, object : OnBarcodeRowClickListener {
            override fun onBarcodeRowClickListener(item: BarcodeVO) {

            }
        }, showDelete = false)
        customDialogList.getRecyclerView().adapter = expeditionAdapter

        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)


    }


}