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.FragmentExpeditionScanBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.component.CustomDialogTwoButtons
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.ExpeditionScanAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.*
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionScanFragment (
    var itemExpeditionTruckVO: ItemExpeditionTruckVO? = null,
    var itemPalletVO: ItemPalletVO? = null
) : BaseFragment<FragmentExpeditionScanBinding, ExpeditionScanViewModel>(
    ExpeditionScanViewModel::class) {

    private var adapter : ExpeditionScanAdapter? = null
    private var onPalletClickListener: OnPalletClickListener? = null
    private var onComprobarPalletViewClickListener: OnComprobarPalletViewClickListener? = null
    private lateinit var customDialogList: CustomDialogList
    private lateinit var customDialogTwoButtons: CustomDialogTwoButtons

    private var listExpeditions:ArrayList<BarcodeVO> = ArrayList()
    private var expeditionAdapter : BarcodeAdapter? = null
    private lateinit var customDialog: CustomDialog
    var mperror: MediaPlayer? = null

    companion object {
        fun newInstance(item: ItemExpeditionTruckVO,itemPalletVO: ItemPalletVO) =
            ExpeditionScanFragment(item,itemPalletVO)
    }

    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_scan

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

        super.onCreate(savedInstanceState)
    }

    override fun init() {
        customDialog = CustomDialog(requireContext())
        customDialogList = CustomDialogList(requireContext())
        customDialogTwoButtons = CustomDialogTwoButtons(requireContext())
        binding.expeditionScanDetailPallet.text = getString(R.string.pallet) + " " + itemPalletVO!!.Pallet
        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.expeditionScanList(getData(USER),
            getData(PASSWORD),itemPalletVO!!.Pallet)
        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.expeditionScanList(getData(USER),
                        getData(PASSWORD),itemPalletVO!!.Pallet)
                }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){
            loadExpeditionScanList.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=="1"){
                            mperror?.start()

                }}
            })


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

                }else{
                    viewModel.expeditionScanList(getData(USER),
                        getData(PASSWORD),itemPalletVO!!.Pallet)
                }
            })
        }
    }

    private fun printExpeditionList(it: ItemExpeditionScanList){

            binding.splashProgress.visibility = View.GONE
            val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
            adapter = ExpeditionScanAdapter(it.list,object: OnScanLongClickListener{
                override fun onScanLongClickListener(itemExpeditionScan: ItemExpeditionScanVO) {
                    customDialogTwoButtons.setTitle(getString(R.string.ticket)+itemExpeditionScan.Ticket+getString(R.string.pallet)+itemPalletVO!!.Pallet)
                        .setDescription(getString(R.string.expedit)+itemExpeditionScan.expeditionFk)
                        .setOkButton(getString(R.string.delete)){
                            binding.splashProgress.visibility = View.VISIBLE
                            viewModel.expeditionScanDel(getData(USER),
                                getData(PASSWORD),itemExpeditionScan.id)
                            customDialogTwoButtons.dismiss()
                        }.setKoButton(getString(R.string.cancel)){
                            customDialogTwoButtons.dismiss()
                        }.show()
                }

            })
            binding.expeditionPalletRecyclerview.adapter = adapter
            binding.expeditionPalletRecyclerview.layoutManager = lm


    }

    private fun expeditionScanAdd(){
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.expeditionScanAdd(usuario = getData(USER),
            getData(PASSWORD),vPalletFk = itemPalletVO!!.Pallet,vTruckFk = itemExpeditionTruckVO!!.truckFk)

    }

    private fun showScanExpeditions(it: ItemScanList){

        listExpeditions = ArrayList()
        binding.splashProgress.visibility = View.GONE
        it.list.forEach {
            if(it.expeditionFk != "0")
                listExpeditions.add(BarcodeVO(code = it.expeditionFk))
        }
        customDialogList.setTitle(getString(R.string.pallet) +" "+ itemPalletVO!!.Pallet+" \n("+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.ok)){
                    customDialog.dismiss()
                }.show()
            }

            customDialogList.dismiss()


        }.setKoButton(getString(R.string.close)){
            ma.hideKeyboard(customDialogList.getEditText())
            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()) {

                        listExpeditions.add(BarcodeVO(code = customDialogList.getValue()))
                    viewModel.expeditionScanPut(
                        getData(USER),
                        getData(PASSWORD),
                        it.list.get(0).palletFk,
                        customDialogList.getValue()
                    )

                  checkRouteExpeditionScanPut(getData(USER),
                      getData(PASSWORD),it.list.get(0).palletFk,customDialogList.getValue())

                    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)


    }

    private fun checkRouteExpeditionScanPut(user: String, password: String, palletFk: String, expedition: String){

       viewModel.checkRouteExpeditionScanPut(user,password,palletFk,expedition)


    }

}