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


import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionPalletDetailBinding
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnPalletClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.paletizador.adapter.ExpeditionPalletViewAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletViewListVO
import java.text.SimpleDateFormat
import java.util.*

class ExpeditionPalletDetailFragment(
    var itemExpeditionTruckVO: ItemExpeditionTruckVO? = null,
    var itemPallet: ItemPalletVO? = null
) : BaseFragment<FragmentExpeditionPalletDetailBinding, ExpeditionPalletDetailViewModel>(
    ExpeditionPalletDetailViewModel::class
) {

    private var adapter: ExpeditionPalletViewAdapter? = null

    // private lateinit var customDialogList: CustomDialogList
    private var onPalletClickListener: OnPalletClickListener? = null

    private lateinit var customDialog: CustomDialog


    companion object {
        fun newInstance(item: ItemExpeditionTruckVO, itemPallet: ItemPalletVO) =
            ExpeditionPalletDetailFragment(item, itemPallet)
    }

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

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

    override fun init() {
        customDialog = CustomDialog(requireContext())
        binding.expeditionPalletDetailPallet.text =
            getString(R.string.pallet) + " " + itemPallet!!.Pallet
        binding.splashProgress.visibility = View.VISIBLE
        ma.hideBottomNavigation(View.GONE)
        binding.mainToolbar.toolbarTitle.text =
            getCURDATE(itemExpeditionTruckVO!!.ETD) + " " +  if (itemExpeditionTruckVO!!.Destino.isNullOrEmpty()) {

                itemExpeditionTruckVO!!.description
            }else{
                itemExpeditionTruckVO!!.Destino
            }

        setToolBar()
        setEvents()
        viewModel.expeditionPallet_List(
            getData(USER),
            getData(PASSWORD), itemPallet!!.Pallet
        )
        super.init()
    }

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

        binding.buttonOk.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 iconEditar: Drawable =
            resources.getDrawable(R.drawable.ic_mode_edit_black_24dp, resources.newTheme())
        val iconBorrar: Drawable =
            resources.getDrawable(R.drawable.ic_delete_forever_black_24dp, resources.newTheme())
        val iconPrint: Drawable =
            resources.getDrawable(R.drawable.ic_print_black_24dp, resources.newTheme())
        listIcons.add(iconEditar)
        listIcons.add(iconBorrar)
        listIcons.add(iconPrint)
        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), itemPallet!!.Pallet
                        )
                    } else if (item == iconEditar) {
                        onPalletClickListener!!.onPalletClickListener(
                            itemExpeditionTruckVO!!,
                            itemPallet!!
                        )
                    } else if (item == iconBorrar) {

                        customDialog.setTitle(getString(R.string.info))
                        customDialog.setDescription(getString(R.string.messageConfirm))
                        customDialog.setOkButton(getString(R.string.delete)) {
                            binding.splashProgress.visibility = View.VISIBLE
                            viewModel.expeditionPalletDel(
                                getData(USER),
                                getData(PASSWORD), itemPallet!!.Pallet
                            )
                            customDialog.dismiss()
                        }
                        customDialog.setKoButton(getString(R.string.cancel)) {
                            customDialog.dismiss()
                        }
                        customDialog.show()

                    } else if (item == iconPrint) {
                        binding.splashProgress.visibility = View.VISIBLE

                        if (ma.havePrinter() && ma.haveSector()) {
                            (getString(R.string.Imprimiendo) + getData(PRINTERNAME)).toast(
                                requireContext()
                            )
                            viewModel.expeditionPalletPrintSet(
                                getData(USER),
                                getData(PASSWORD),
                                itemPallet!!.Pallet,
                                getData(SECTORFK)
                            )
                        } else {
                            ma.messageWithSound(
                                getString(R.string.printerFault),
                                isError = true,
                                true,
                                getString(R.string.printError),
                                false
                            )
                        }
                    }
                }
            })
        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) }
            })

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

            responsePrintPallet.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, true, isToasted = false)

                } else {
                    binding.splashProgress.visibility = View.VISIBLE
                    viewModel.expeditionState_addByPallet(
                        getData(USER),
                        getData(PASSWORD),
                        itemPallet!!.Pallet,
                        "PALLETIZED"
                    )

                }
            })
        }
    }

    private fun printExpeditionList(it: ItemPalletViewListVO) {
        binding.splashProgress.visibility = View.GONE
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = ExpeditionPalletViewAdapter(it.list)
        binding.expeditionPalletRecyclerview.adapter = adapter
        binding.expeditionPalletRecyclerview.layoutManager = lm
    }

}