package es.verdnatura.presentation.view.feature.main.activity

import PhotosFragment
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Build
import android.view.Menu
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.MutableLiveData
import com.google.android.material.navigation.NavigationBarView
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.databinding.ActivityMainBinding
import es.verdnatura.domain.ConstAndValues.MAINACTIVITY
import es.verdnatura.domain.ConstAndValues.PREITEMPICKER
import es.verdnatura.domain.ConstAndValues.PRINTERFK
import es.verdnatura.domain.ConstAndValues.PRINTERFKDEFAULT
import es.verdnatura.domain.ConstAndValues.RENEWINTERVAL
import es.verdnatura.domain.ConstAndValues.RENEWPERIOD
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.ConstAndValues.SECTORFKDEFAULT
import es.verdnatura.domain.ConstAndValues.TOKEN
import es.verdnatura.domain.ConstAndValues.TOKENCREATED
import es.verdnatura.domain.ConstAndValues.TTL
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseActivity
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialogMainActivity
import es.verdnatura.presentation.view.feature.ajustes.fragment.AjustesFragment
import es.verdnatura.presentation.view.feature.articulo.fragment.ItemCardFragment
import es.verdnatura.presentation.view.feature.articulo.fragment.ItemProposalFragment
import es.verdnatura.presentation.view.feature.buffer.fragment.BufferFragment
import es.verdnatura.presentation.view.feature.buffer.fragment.BufferLoadFragment
import es.verdnatura.presentation.view.feature.buscaritem.fragment.BuscarItemFragment
import es.verdnatura.presentation.view.feature.claim.fragment.ClaimFragment
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionFragment
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionFragmentPicker
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionFragmentPickerNew
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionFragmentPreChecker
import es.verdnatura.presentation.view.feature.collection.fragment.CollectionShowTicketFragment
import es.verdnatura.presentation.view.feature.controlador.fragment.ControladorFragment
import es.verdnatura.presentation.view.feature.controlador.fragment.WebFragment
import es.verdnatura.presentation.view.feature.controlvehiculo.fragment.ControlVehiculoFragment
import es.verdnatura.presentation.view.feature.controlvehiculo.fragment.ControlVehiculoUsuarioFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.InfoFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.LoadUnloadFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.LogExpeditionFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.RoutesFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.SummaryFragment
import es.verdnatura.presentation.view.feature.delivery.fragments.TicketsFragment
import es.verdnatura.presentation.view.feature.delivery.model.ClientTicketSalix
import es.verdnatura.presentation.view.feature.diadeventa.fragment.DayOfSaleFragment
import es.verdnatura.presentation.view.feature.historicoarticulo.fragment.HistoricoArticuloFragment
import es.verdnatura.presentation.view.feature.historicoshelving.fragment.ItemShelvingLogFragment
import es.verdnatura.presentation.view.feature.historicoshelvinglog.fragment.ShelvingLogFragment
import es.verdnatura.presentation.view.feature.historicovehiculo.fragment.HistoricoVehiculoFragment
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryFragment
import es.verdnatura.presentation.view.feature.inventario.fragment.InventaryParkingFragment
import es.verdnatura.presentation.view.feature.login.fragment.LoginViewModel
import es.verdnatura.presentation.view.feature.login.model.RenewToken
import es.verdnatura.presentation.view.feature.main.model.ItemMenuVO
import es.verdnatura.presentation.view.feature.packaging.fragment.ObservFragment
import es.verdnatura.presentation.view.feature.packaging.fragment.PackagingCountFragment
import es.verdnatura.presentation.view.feature.packaging.fragment.PackagingSummaryFragment
import es.verdnatura.presentation.view.feature.packaging.fragment.SupplierFragment
import es.verdnatura.presentation.view.feature.packingHolland.fragment.PackingHollandFragment
import es.verdnatura.presentation.view.feature.paletizador.fragment.*
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckVO
import es.verdnatura.presentation.view.feature.paletizador.model.ItemPalletVO
import es.verdnatura.presentation.view.feature.parking.fragment.ParkingFragment
import es.verdnatura.presentation.view.feature.pasillero.fragment.PasilleroFragment
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import es.verdnatura.presentation.view.feature.precontrol.PreControladorFragment
import es.verdnatura.presentation.view.feature.presacador.fragment.EndSacadorFragment
import es.verdnatura.presentation.view.feature.qr.QrFragment
import es.verdnatura.presentation.view.feature.reubication.fragment.ReubicationCollectionFragment
import es.verdnatura.presentation.view.feature.reubication.fragment.ReubicationFragment
import es.verdnatura.presentation.view.feature.reubication.model.Reubication
import es.verdnatura.presentation.view.feature.sacador.fragment.SacadorFragment
import es.verdnatura.presentation.view.feature.sacador.fragment.SacadorFragmentNew
import es.verdnatura.presentation.view.feature.sacador.fragment.showticket.ShowTicketFragment
import es.verdnatura.presentation.view.feature.sacador.model.CollectionTicket
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.ticket.fragment.TicketAdvanceFragment
import es.verdnatura.presentation.view.feature.ubicador.fragment.AutomaticAddItemFragment
import es.verdnatura.presentation.view.feature.ubicador.fragment.UbicadorFragment
import es.verdnatura.presentation.view.feature.workermistake.fragment.PackingMistakeFragment
import es.verdnatura.presentation.view.feature.workermistake.fragment.WorkermistakeFragment
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import timber.log.Timber.d
import java.util.Date
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit

class MainActivity : BaseActivity<ActivityMainBinding>(), OnPasillerosItemClickListener,
    OnTruckClickListener, OnPalletClickListener, OnComprobarPalletViewClickListener,
    OnCollectionSelectedListener, OnCollectionTicketSelectedListener, MainActivityListener {

    private var lastBottomMenuItemSelected: ItemMenuVO? = null
    private lateinit var customDialog: CustomDialogMainActivity
    private var firstItem: ItemMenuVO? = null
    private var fm = supportFragmentManager
    var mperror: MediaPlayer? = null
    var mpok: MediaPlayer? = null
    private var mpErrorRepeat: MediaPlayer? = null
    private var scheduledFuture: ScheduledFuture<*>? = null
    private var scheduledExecutor: ScheduledExecutorService? = null
    private val _renewTokenResponse = MutableLiveData<RenewToken>()
    private lateinit var networkUtils: NetworkUtilsApp
    private var myTimeUserInteraction = (System.currentTimeMillis() / 1000 / 3600)
    private var comeFromDelivery: Boolean? = null
    override fun getLayoutId(): Int = R.layout.activity_main

    override fun onPause() {
        super.onPause()
        scheduledFuture?.cancel(false)

    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onResume() {
        super.onResume()
        try {
            if (scheduledFuture?.isCancelled == true) {
                startRepeatingTask(mobileApplication.dataStoreApp.readDataStoreKey(RENEWINTERVAL))
            }
            networkUtils.registerNetworkCallback()
        } catch (e: Exception) {
            e.message.toString().toast(baseContext)
        }

    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {

        mperror = MediaPlayer.create((this), R.raw.error)
        mpok = MediaPlayer.create((this), R.raw.ok)
        mpErrorRepeat = MediaPlayer.create((this), R.raw.errorrepeat)
        customDialog = CustomDialogMainActivity(this)
        setFragments()
        setBottomMenuFragment()
        setRegisterNetwork()
        (application as MobileApplication).setMainListener(this)
        //Tarea
        //printBluetooth()

    }

    private fun printBluetooth() {

        /*var str =
            "<113>Mate Technologies<100>Website: www.matetech.in\nEmail: matetusshar@gmail.com<IMAGE>1#$imgpath"*/
        var str = "<BARCODE>0#100#50#2132137538472<QR>1#40#testing text"
        str =
            "$str<HTML><div><div style=\"float:left;\"><b>This is left</b></div><div style=\"float:right;font-size:15px;\">This is right</div></div>"

        val sendIntent = Intent()
        sendIntent.action = Intent.ACTION_SEND
        sendIntent.setPackage("mate.bluetoothprint")
        sendIntent.putExtra(Intent.EXTRA_TEXT, str)
        sendIntent.type = "text/plain"
        startActivity(sendIntent)
    }

    private fun setRegisterNetwork() {
        networkUtils = NetworkUtilsApp(this, application as MobileApplication)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun startRepeatingTask(myInterval: Long) {

        scheduledExecutor = Executors.newSingleThreadScheduledExecutor()
        scheduledFuture = scheduledExecutor?.scheduleAtFixedRate(
            {
                runOnUiThread {
                    checkTokenRenew()
                }
            }, 0, myInterval, TimeUnit.SECONDS
        )
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onDestroy() {
        super.onDestroy()
        scheduledExecutor?.shutdown()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setFragments() {
        try {
            val uriImage = intent.data
            startRepeatingTask(
                mobileApplication.dataStoreApp.readDataStoreKey(RENEWINTERVAL)
            )
            if (uriImage != null && uriImage is Uri) {
                onPasillerosItemClickListener(
                    PasillerosItemVO(
                        30,
                        R.drawable.photo_camera,
                        getString(R.string.titlePhotos),
                        R.string.titlePhotos,
                        getString(
                            R.string.titlePhotosDescrip
                        )

                    ), uriImage.toString()
                )
            } else {
                if (haveSector() && havePrinter()) addFragment(
                    PasilleroFragment.newInstance(getString(R.string.main), true),
                    R.id.main_frame_layout,
                    PasilleroFragment.TAG,
                    false
                )
                else addFragment(
                    AjustesFragment.newInstance(),
                    R.id.main_frame_layout,
                    AjustesFragment.TAG,
                    false
                )

            }

        } catch (exception: Exception) {
            getString(R.string.error).toast(this)
        }

    }

    fun haveSector(): Boolean {
        return mobileApplication.dataStoreApp.readDataStoreKey<Int>(SECTORFK) != SECTORFKDEFAULT
    }

    fun havePrinter(): Boolean {
        return mobileApplication.dataStoreApp.readDataStoreKey<Int>(PRINTERFK) != PRINTERFKDEFAULT
    }

    @DelicateCoroutinesApi
    fun setBottomMenuFragment() {
        val bottomMenu = binding.mainBottomNavigation
        bottomMenu.labelVisibilityMode = NavigationBarView.LABEL_VISIBILITY_UNLABELED
        bottomMenu.itemIconTintList = null
        GlobalScope.launch(Dispatchers.Main) {
            val bottomMenuItems: ArrayList<ItemMenuVO> = ArrayList()

            bottomMenuItems.add(
                ItemMenuVO(
                    0,
                    title = getString(R.string.titleCorridors),
                    defaultImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_init_ui
                    ),
                    selectedImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_init_ui_selected
                    )
                )
            )

            bottomMenuItems.add(
                ItemMenuVO(
                    1,
                    title = getString(R.string.verticket),
                    defaultImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_eye_ui
                    ),
                    selectedImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_eye_ui_selected
                    )
                )
            )

            bottomMenuItems.add(
                ItemMenuVO(
                    2,
                    title = getString(R.string.Parking),
                    defaultImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_parking_ui
                    ),
                    selectedImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_parking_ui_selected
                    )
                )
            )

            bottomMenuItems.add(
                ItemMenuVO(
                    3,
                    title = getString(R.string.Ajustes),
                    defaultImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_setting_ui
                    ),
                    selectedImage = ContextCompat.getDrawable(
                        applicationContext, R.drawable.ic_setting_ui_selected
                    )
                )
            )

            // Add al items to menu view
            bottomMenuItems.forEach {
                bottomMenu.menu.add(Menu.NONE, it.id, Menu.NONE, it.title).icon = it.defaultImage
            }


            if (haveSector()) {
                // Select first item by default
                firstItem = bottomMenuItems.first()
                bottomMenu.selectedItemId = firstItem!!.id
                bottomMenu.menu.findItem(firstItem!!.id).icon = firstItem!!.selectedImage
                lastBottomMenuItemSelected = firstItem
            } else {
                // Select last item by default
                val lastItem = bottomMenuItems.last()
                bottomMenu.selectedItemId = lastItem.id
                bottomMenu.menu.findItem(lastItem.id).icon = lastItem.selectedImage
                lastBottomMenuItemSelected = lastItem
            }


            bottomMenu.setOnNavigationItemSelectedListener { menuItem ->
                // Get selected item from itemList and apply ui changes to menu view
                val selectedItemMenu = bottomMenuItems.find { menuItem.itemId == it.id }
                menuItem.icon = selectedItemMenu?.selectedImage

                // Get last selected item and disable it
                bottomMenu.menu.findItem(lastBottomMenuItemSelected?.id!!).icon =
                    lastBottomMenuItemSelected?.defaultImage
                lastBottomMenuItemSelected = selectedItemMenu


                when (selectedItemMenu?.title) {

                    getString(R.string.titleCorridors) -> {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        delete_Fragments()
                        addFragment(
                            PasilleroFragment.newInstance(getString(R.string.main), true),
                            R.id.main_frame_layout,
                            PasilleroFragment.TAG,
                            false
                        )

                    }

                    getString(R.string.verticket) -> {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        delete_Fragments()
                        addFragment(
                            ShowTicketFragment.newInstance(getString(R.string.main)),
                            R.id.main_frame_layout,
                            MAINACTIVITY.TAG,
                            false
                        )

                    }

                    getString(R.string.Parking) -> {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        delete_Fragments()
                        addFragment(
                            ParkingFragment.newInstance(getString(R.string.main)),
                            R.id.main_frame_layout,
                            MAINACTIVITY.TAG,
                            false
                        )

                    }

                    getString(R.string.Ajustes) -> {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        delete_Fragments()
                        addFragment(
                            AjustesFragment.newInstance(),
                            R.id.main_frame_layout,
                            AjustesFragment.TAG,
                            false
                        )
                    }

                }

                true
            }/* sergio: de esta manera no repinta el icono del menu seleccionado */
            bottomMenu.setOnNavigationItemReselectedListener {

                when (it.title) {

                    getString(R.string.titleCorridors) -> {
                        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
                        delete_Fragments()
                        addFragment(
                            PasilleroFragment.newInstance(getString(R.string.main), true),
                            R.id.main_frame_layout,
                            PasilleroFragment.TAG,
                            false
                        )

                    }
                }

            }

        }
    }

    private fun delete_Fragments() {
        fm.getFragments().forEach {
            val fragment: Fragment? = supportFragmentManager.findFragmentByTag(it.tag.toString())
            if (fragment != null) supportFragmentManager.beginTransaction().remove(fragment)
                .commit()
        }
    }

    override fun onPasillerosItemClickListener(
        item: PasillerosItemVO, entryPoint: String, param: Any?
    ) {

        when (item.title) {

            //BUFFERS
            getString(R.string.titlePalletizar) -> {
                addFragmentOnTop(ExpeditionTruckListFragment.newInstance())
            }

            getString(R.string.titlePalletizers) -> {

                addFragmentOnTop(
                    PasilleroFragment.newInstance(
                        getString(R.string.titlePalletizers), isInitMenu = false
                    )
                )

            }

            getString(R.string.historicals) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(item.title, isInitMenu = false),
                )
            }

            getString(R.string.titleControllers) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(item.title, isInitMenu = false),
                )
            }

            getString(R.string.titleOther) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(item.title, isInitMenu = false),
                )
            }

            getString(R.string.titleChecker) -> {
                addFragmentOnTop(ControladorFragment.newInstance())
            }

            getString(R.string.titleCorridors) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(item.title, isInitMenu = false),
                )
            }

            getString(R.string.titlePrevious) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(item.title, isInitMenu = false),
                )
            }

            getString(R.string.titleExpeditionState) -> {
                // addFragment(ExpeditionStateFragment.newInstance(entryPoint),R.id.main_frame_layout, ExpeditionTruckListFragment.TAG,false)
                addFragmentOnTop(ExpeditionStateFragment.newInstance(item.title))
            }

            getString(R.string.titleScanExpedition) -> {
                addFragmentOnTop(ExpeditionScanSorterFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferManegement) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(
                        item.title, isInitMenu = false
                    )
                )
            }

            getString(R.string.titleClaims) -> {
                addFragmentOnTop(
                    PasilleroFragment.newInstance(
                        item.title, isInitMenu = false
                    )
                )

            }

            getString(R.string.titleUserControlVehicle) -> {
                addFragmentOnTop(ControlVehiculoUsuarioFragment.newInstance(entryPoint.toInt()))
            }

            /* getString(R.string.titlePrePicker) -> {
                 addFragmentOnTop(PreSacadorFragment.newInstance())
             }*/
            getString(R.string.titleDayOfSale) -> {
                addFragmentOnTop(DayOfSaleFragment(item.title))
            }

            getString(R.string.titleShowTicket) -> {
                addFragmentOnTop(ShowTicketFragment.newInstance(getString(R.string.titleCorridors)))
            }

            getString(R.string.titleHistoricalVehicle) -> {
                addFragmentOnTop(ControlVehiculoFragment.newInstance(HistoricoVehiculoFragment.TAG))
            }

            getString(R.string.titleItemConsult) -> {
                addFragmentOnTop(ItemCardFragment.newInstance(entryPoint))
            }

            getString(R.string.titleSearchSimilarItems) -> {
                addFragmentOnTop(ItemProposalFragment.newInstance(entryPoint.toInt()))
            }

            //segio: esta opción no se muestra, solo es accesible para añadir fragmentos de otras partes.
            getString(R.string.titleHistoricalHide) -> {
                addFragmentOnTop(HistoricoVehiculoFragment.newInstance(entryPoint))
            }

            getString(R.string.Parking) -> {
                addFragmentOnTop(ParkingFragment.newInstance(""))
            }

            getString(R.string.titleItemSearch) -> {

                addFragmentOnTop(
                    BuscarItemFragment.newInstance(
                        if (entryPoint == "") {
                            null
                        } else {
                            entryPoint.toInt()
                        }
                    )
                )
            }

            getString(R.string.titleHistorical) -> {
                addFragmentOnTop(HistoricoArticuloFragment.newInstance(entryPoint.toInt()))
            }

            getString(R.string.titleInventory) -> {
                addFragmentOnTop(InventaryFragment.newInstance())
            }

            getString(R.string.titleUbicator) -> {
                addFragmentOnTop(UbicadorFragment.newInstance(entryPoint))
            }

            getString(R.string.titleAuto) -> {
                addFragmentOnTop(AutomaticAddItemFragment.newInstance(entryPoint, item.title))
            }

            /*    getString(R.string.titleControllersAction) -> {
                    addFragmentOnTop(AutomaticAddItemFragment.newInstance(entryPoint, item.title))
                }*/

            getString(R.string.titlePickers) -> {
                //addFragmentOnTop(SacadorFragment.newInstance())
                addFragmentOnTop(ControlVehiculoFragment.newInstance(""))
            }

            "Sacador Test" -> {
                addFragmentOnTop(SacadorFragmentNew.newInstance("PREPARED"))

            }

            getString(R.string.titleWebViewer) -> {
                // el entryPoint de WebFragment se le pasa un JSON del tipo {"entryPoint":"itemScanned","web":"www.google.com}
                addFragmentOnTop(WebFragment.newInstance(entryPoint))
            }
            //Menu qr
            getString(R.string.titleQrReader) -> {
                addFragmentOnTop(QrFragment.newInstance(item.title))
            }

            //Menu buffer
            getString(R.string.titleBufferEmpty) -> {
                addFragmentOnTop(BufferFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferFill) -> {
                addFragmentOnTop(BufferFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferAccumulate) -> {
                addFragmentOnTop(BufferFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferOff) -> {
                addFragmentOnTop(BufferFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferload) -> {
                addFragmentOnTop(BufferLoadFragment.newInstance(item.title))
            }

            getString(R.string.titleBufferStrapping) -> {
                addFragmentOnTop(BufferFragment.newInstance(item.title))
            }

            getString(R.string.titlePreControl) -> {
                addFragmentOnTop(PreControladorFragment.newInstance())
            }

            getString(R.string.titleShelvingHistorical) -> {
                addFragmentOnTop(ItemShelvingLogFragment.newInstance(item.title))

            }

            getString(R.string.titleLogShelving) -> {
                addFragmentOnTop(ShelvingLogFragment.newInstance(item.title))
            }

            getString(R.string.titleWorkerMistake) -> {
                addFragmentOnTop(WorkermistakeFragment.newInstance(item.title))
            }

            getString(R.string.titlePackingMistake) -> {
                addFragmentOnTop(PackingMistakeFragment.newInstance(item.title))
            }

            getString(R.string.titlePrePicker) -> {
                addFragmentOnTop(SacadorFragment.newInstance("PREITEMPICKER"))
            }

            getString(R.string.titleClaimUbication) -> {
                addFragmentOnTop(ClaimFragment.newInstance(item.title))
            }

            getString(R.string.titleReUbicator) -> {
                addFragmentOnTop(ReubicationFragment.newInstance(item.title))
            }

            getString(R.string.titleCMRState) -> {
                addFragmentOnTop(CmrExpeditionPalletFragment.newInstance(item.title))
            }

            getString(R.string.scanPlatform) -> {
                addFragmentOnTop(PalletScanFragment.newInstance(item.title, "receive"))
            }

            getString(R.string.titleScanPalletizar) -> {
                addFragmentOnTop(PalletScanFragment.newInstance(item.title, "get"))
            }

            getString(R.string.titlePackaging) -> {
                addFragmentOnTop(SupplierFragment.newInstance(item.title))
            }

            getString(R.string.titlePackagingCount) -> {
                addFragmentOnTop(PackagingCountFragment.newInstance(item.title))
            }

            getString(R.string.titlePackagingObs) -> {
                addFragmentOnTop(ObservFragment.newInstance(item.title))
            }

            getString(R.string.titlePackagingSummary) -> {
                addFragmentOnTop(PackagingSummaryFragment.newInstance(item.title))
            }

            getString(R.string.selfConsumption) -> {
                addFragmentOnTop(UbicadorFragment.newInstance(entryPoint, true))
            }

            getString(R.string.titlePackingHolland) -> {
                addFragmentOnTop(PackingHollandFragment.newInstance(item.title))
            }

            getString(R.string.titleDelivery) -> {

                addFragmentOnTop(
                    RoutesFragment.newInstance(getString(R.string.titleDeliveryRoute)),
                    getString(R.string.titleDeliverySummary)
                )

            }

            getString(R.string.titleInfo) -> {
                addFragmentOnTop(
                    InfoFragment.newInstance(item.title), if (comeFromDelivery == true) {
                        getString(R.string.titleInfo)
                    } else {
                        null
                    }
                )

            }

            getString(R.string.titleLog) -> {

                addFragmentOnTop(
                    LogExpeditionFragment.newInstance(item.title), if (comeFromDelivery == true) {
                        getString(R.string.titleLog)
                    } else {
                        null
                    }
                )

            }

            getString(R.string.titleLoadTruck) -> {
                addFragmentOnTop(
                    LoadUnloadFragment.newInstance(item.title, "ON DELIVERY", entryPoint),
                    if (comeFromDelivery == true) {
                        getString(R.string.titleLoadTruck)
                    } else {
                        getString(R.string.titleLoadTruck)
                    }
                )

            }

            getString(R.string.titleUnLoadTruck) -> {

                addFragmentOnTop(
                    LoadUnloadFragment.newInstance(
                        item.title, "DELIVERED", entryPoint, if (param != null) {
                            param as ArrayList<ClientTicketSalix>
                        } else {
                            null
                        }
                    ), if (comeFromDelivery == true) {
                        getString(R.string.titleUnLoadTruck)
                    } else {
                        getString(R.string.titleUnLoadTruck)
                    }, delete = true
                )

            }

            getString(R.string.titleDeliverySummary) -> {

                addFragmentOnTop(
                    SummaryFragment.newInstance(item.title, "ON DELIVERY", entryPoint.toInt()),
                    if (comeFromDelivery == true) {
                        getString(R.string.titleDeliverySummary)
                    } else {
                        null
                    }
                )

            }

            getString(R.string.titleDeliveryRoute) -> {

                addFragmentOnTop(
                    RoutesFragment.newInstance(item.title), if (comeFromDelivery == true) {
                        getString(R.string.titleDeliverySummary)
                    } else {
                        null
                    }
                )

            }

            getString(R.string.titlePhotos) -> {
                addFragmentOnTop(
                    PhotosFragment.newInstance(item.title, entryPoint)
                )
            }

            getString(R.string.ticketAdvance) -> {
                addFragmentOnTop(
                    TicketAdvanceFragment.newInstance(item.title)
                )
            }

            getString(R.string.testing) -> {
                // addFragmentOnTop(
                // PhotosFragment.newInstance(item.title))
                //addFragmentOnTop(testPrint.newInstance(item.title))
            }

            getString(R.string.titleInventoryParking) -> {
                addFragmentOnTop(InventaryParkingFragment.newInstance(item.title))
            }

            getString(R.string.tickets) -> {
                addFragmentOnTop(TicketsFragment.newInstance(item.title, entryPoint))
            }
        }

    }

    fun addFragmentOnTop(fragment: Fragment?, name: String? = null, delete: Boolean = false) {

        if (delete) {
            supportFragmentManager.beginTransaction().apply {

                val currentFragment =
                    supportFragmentManager.findFragmentById(R.id.main_frame_layout)
                currentFragment?.let {
                    remove(it)
                }
            }
        }
        supportFragmentManager.beginTransaction().replace(R.id.main_frame_layout, fragment!!)
            .addToBackStack(name).commitAllowingStateLoss()

    }

    override fun onBackPressed() {

        var index = supportFragmentManager.backStackEntryCount - 1
        var backEntry = ""
        if (index >= 0) {
            backEntry = supportFragmentManager.getBackStackEntryAt(index).name.toString()

            if (backEntry.contains(getString(R.string.titleLoadTruck)) || backEntry.contains(
                    getString(R.string.titleUnLoadTruck)
                )
            ) {
                if (LoadUnloadFragment.scanned) {
                    customDialog.setTitle(getString(R.string.packagesNotScanned))
                        .setDescription(getString(R.string.savePackages))
                        .setOkButton(getString(R.string.yes)) {
                            customDialog.dismiss()
                        }.setKoButton(getString(R.string.no)) {
                            backStackFragments(backEntry)
                            customDialog.dismiss()
                        }.show()

                } else {
                    backStackFragments(backEntry)
                }
            } else {
                backStackFragments(backEntry)
            }
        } else {
            backStackFragments(backEntry)
        }
    }

    private fun backStackFragments(backEntry: String) {
        try {
            fm.executePendingTransactions()
        } catch (ex: Exception) {
            d("$ex")
        }

        if (fm.backStackEntryCount > 0) {

            fm.popBackStackImmediate()

            if (!backEntry.isNullOrBlank())

                if (backEntry!!.contains("fragment.ExpeditionPalletDetailFragment.Companion")) {
                    addFragmentOnTop(ExpeditionTruckListFragment.newInstance())
                }
            if (backEntry!!.contains(getString(R.string.titleLog)) || backEntry!!.contains(
                    getString(
                        R.string.titleInfo
                    )
                )
            ) {
                finish()
            }

        } else {
            customDialog.setTitle(getString(R.string.closeSession))
                .setDescription(getString(R.string.sureCloseSession))
                .setOkButton(getString(R.string.exit)) {
                    customDialog.dismiss()
                    //Borrar Token
                    runBlocking { mobileApplication.dataStoreApp.editDataStoreKey(TOKEN, "") }
                    finish()

                }.setKoButton(getString(R.string.cancel)) {
                    customDialog.dismiss()
                }.show()
        }
    }

    override fun onTruckClickListener(item: ItemExpeditionTruckVO, entryPoint: String) {
        addFragmentOnTop(ExpeditionPalletFragment.newInstance(item))

    }

    override fun onPalletClickListener(
        itemTruck: ItemExpeditionTruckVO, itemPallet: ItemPalletVO
    ) {

        addFragmentOnTop(ExpeditionScanFragment.newInstance(itemTruck, itemPallet))
    }

    override fun onComprobarPalletViewClickListener(
        itemTruck: ItemExpeditionTruckVO, itemPallet: ItemPalletVO
    ) {

        addFragmentOnTop(ExpeditionPalletDetailFragment.newInstance(itemTruck, itemPallet))

    }

    fun onComprobarPalletFromPalletScan(
        itemTruck: ItemExpeditionTruckVO, itemPallet: ItemPalletVO
    ) {
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)

        addFragment(
            ExpeditionPalletDetailFragment.newInstance(itemTruck, itemPallet),
            R.id.main_frame_layout,
            ExpeditionPalletDetailFragment.TAG,
            true
        )

    }

    override fun onCollectionSelected(collection: CollectionTicket, type: String) {

        addFragmentOnTop(CollectionFragmentPickerNew.newInstance(collection, type))

    }

    override fun onCollectionSelected(collection: CollectionVO, type: String) {

        when (type) {
            PREITEMPICKER -> {

                addFragmentOnTop(EndSacadorFragment.newInstance(collection, type))
            }

            "SHOWTICKET" -> {
                addFragmentOnTop(CollectionShowTicketFragment.newInstance(collection, type))
            }

            //Tarea 4711
            "PRECHECKER" -> {
                addFragmentOnTop(CollectionFragmentPreChecker.newInstance(collection, type))
            }

            "PREPARED" -> {
                addFragmentOnTop(CollectionFragmentPicker.newInstance(collection, type))
            }

            else -> {
                addFragmentOnTop(CollectionFragment.newInstance(collection, type))
            }
        }

    }

    //sergio:se llama al pulsar sobre el coche IN desde Sacador
    fun onVehicleSelected(tag: String) {
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)

        // se pone a true en la pila para que cuando se vuelva atrás permanezca ya que se borran todos los fragmentos desde otras opciones
        addFragment(
            ControlVehiculoFragment.newInstance(tag),
            R.id.main_frame_layout,
            ControlVehiculoFragment.TAG,
            true
        )
    }

    fun openSummaryFragment(route: Int, state: String) {
        addFragmentOnTop(
            SummaryFragment.newInstance(
                getString(R.string.titleDeliverySummary), state, route
            )
        )
    }

    fun openFragmentPickers(delete: Boolean) {
        //delete_Fragments()
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
        if (delete) {
            delete_Fragments()
        }
        addFragment(
            SacadorFragment.newInstance("PREPARED"),
            R.id.main_frame_layout,
            SacadorFragment.TAG,
            true

        )

    }

    fun openFragmentUnload(delete: Boolean) {
        //delete_Fragments()
        fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
        if (delete) {
            delete_Fragments()
        }
        addFragment(
            SacadorFragment.newInstance("PREPARED"),
            R.id.main_frame_layout,
            SacadorFragment.TAG,
            true

        )
        //addFragmentOnTop(SacadorFragment.newInstance())

    }

    fun openFragmentExpeditionState() {
        addFragmentOnTop(ExpeditionStateFragment.newInstance(getString(R.string.titleExpeditionState)))

    }

    fun openFragmentReubications(list: MutableList<Reubication>, shelving: String) {
        addFragmentOnTop(ReubicationCollectionFragment.newInstance(list, shelving))

    }

    fun hideBottomNavigation(visible: Int) {
        binding.mainBottomNavigation.visibility = visible
    }

    fun messageWithSound(
        message: String,
        isError: Boolean?,
        isPlayed: Boolean?,
        titleWithError: String = getString(R.string.error),
        isToasted: Boolean? = true
    ) {
        if (isError != null) {
            if (!isError!!) {

                if (isPlayed == true) (mpok?.start())
                if (isToasted!!) message.toast(this, Toast.LENGTH_LONG)
            } else {

                if (isPlayed == true) (mperror?.start())
                if (isToasted != null) {
                    if (isToasted == true) {
                        message.toast(this, Toast.LENGTH_LONG)
                    } else {
                        customDialog.setTitle(titleWithError).setDescription(message)
                            .setOkButton(getString(R.string.accept)) {
                                customDialog.dismiss()
                            }.show()
                    }
                }
            }
        } else {
            mpErrorRepeat?.start()
        }

    }

    override fun onUserInteraction() {
        super.onUserInteraction()
        if ((System.currentTimeMillis() / 1000 / 3600) - myTimeUserInteraction > 4) {

            myTimeUserInteraction = System.currentTimeMillis() / 1000 / 3600
            val loginViewModel = LoginViewModel(application as MobileApplication)
            loginViewModel.deviceLog_addSalix(
                app = getString(R.string.logAppName),
                versionApp = (application as MobileApplication).versionName,
                android_id = (application as MobileApplication).androidId,
                serialnumber = (application as MobileApplication).serialNumber,
                userFk = (application as MobileApplication).userId!!

            )
        }

    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun checkTokenRenew() {
        val renewPeriod = mobileApplication.dataStoreApp.readDataStoreKey<Long>(RENEWPERIOD)
        val min = minOf(mobileApplication.dataStoreApp.readDataStoreKey(TTL), renewPeriod) * 1000
        if (Date().time < (min + mobileApplication.dataStoreApp.readDataStoreKey<Long>(TOKENCREATED))) {

            val loginViewModel = LoginViewModel(application as MobileApplication)

            loginViewModel.renewTokenResponse.observe(this) { renewToken ->
                if (!renewToken.isError) {
                    runBlocking {
                        mobileApplication.dataStoreApp.editDataStoreKey(TOKEN, renewToken.id)
                        mobileApplication.dataStoreApp.editDataStoreKey(TTL, renewToken.ttl)
                        mobileApplication.dataStoreApp.editDataStoreKey(TOKENCREATED, Date().time)

                    }
                }
            }
            loginViewModel.renewToken()

        }
    }

    override fun onApplicationEventAnimation(visibility: Int) {
        binding.splashAnimation.visibility = visibility
    }

}
