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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnCollectionSelectedListener
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.presacador.adapter.PreCollectionAdapter
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO


class InitPreSacadorFragment (
    var entrypoint:String = ""
) :
        BaseFragment<FragmentSacadorBinding, PreSacadorViewModel>(PreSacadorViewModel::class) {

        private var onCollectionSelectedListener: OnCollectionSelectedListener? = null
        private var goBack: Boolean = false
        private var goBack2: Boolean = false
        private lateinit var customDialog: CustomDialog
        private var collectionsList: ArrayList<CollectionVO> = ArrayList()
        private var adapter: PreCollectionAdapter? = null


        companion object {
            fun newInstance(entryPoint:String) = InitPreSacadorFragment(entryPoint)
        }

        override fun onAttach(context: Context) {
            super.onAttach(context)
            if (context is OnCollectionSelectedListener) onCollectionSelectedListener = context
        }

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


        override fun init() {

            customDialog = CustomDialog(requireContext())
            binding.splashProgress.visibility = View.VISIBLE
            binding.splashProgressTwo.visibility = View.GONE
            setToolBar()
            setEvents()
            viewModel.sectorCollection_get(getData(USER),getData(PASSWORD))
            super.init()


        }

        override fun onPause() {
            goBack = true
            goBack2 = true
            super.onPause()
        }

        private fun setToolBar() {

            ma.hideBottomNavigation(View.VISIBLE)
            binding.mainToolbar.toolbarTitle.text=entrypoint
            binding.mainToolbar.backButton.setOnClickListener{
                ma.onBackPressed()
            }

            val listIcons: ArrayList<ImageView> = ArrayList()
            val iconAdd = ImageView(context)
            iconAdd.setImageResource(R.drawable.ic_add_black_24dp)


            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                iconAdd.tooltipText=getTooltip(R.drawable.ic_add_black_24dp)

            }


            listIcons.add(iconAdd)

            binding.mainToolbar.toolbarIcons.adapter = ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when(item){

                        iconAdd.drawable -> {
                            binding.splashProgress.visibility = View.VISIBLE
                            viewModel.sectorCollection_new(getData(USER),
                                getData(PASSWORD),getData(SECTORFK))
                        }

                    }

                }
            })
            binding.mainToolbar.toolbarIcons.layoutManager =
                LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
        }

        private fun setEvents() {
            binding.sacadorSwipe.setOnRefreshListener {
                viewModel.sectorCollection_get(getData(USER),getData(PASSWORD))
                binding.sacadorSwipe.isRefreshing = false
            }
        }



        override fun observeViewModel() {

            with(viewModel) {

                collectionList.observe(viewLifecycleOwner, Observer {
                    if (!goBack2) binding.splashProgress.visibility = View.GONE
                    createCollectionList(it.list)
                    binding.splashProgress.visibility = View.GONE
                    goBack2 = false
                })

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

                    } else {
                        if (goBack) addCollectionToList(it.response)
                    }
                    goBack = false
                    //sergio:para asegurarnos que aparece en pantalla. En mi movil personal y trabajo no hacia falta.
                    //viewModel.PrecollectionGetSalix(token=getData(TOKEN))
                })
                responseNew.observe(viewLifecycleOwner, Observer {
                    binding.splashProgressTwo.visibility = View.GONE
                    binding.splashProgress.visibility = View.GONE
                    if (it.isError) {
                        ma.messageWithSound(getString(R.string.errorCollectionNew)+ it.errorMessage,true,false)

                    } else {
                        //if (goBack)
                            viewModel.sectorCollection_get(getData(USER),getData(PASSWORD))
                    }
                    goBack = false
                    //sergio:para asegurarnos que aparece en pantalla. En mi movil personal y trabajo no hacia falta.
                    //viewModel.PrecollectionGetSalix(token=getData(TOKEN))
                })
            }
        }

        private fun createCollectionList(collections: List<CollectionVO>) {
            collectionsList = ArrayList()
            collections.forEach {
                collectionsList.add(it)
            }
            val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
            adapter = PreCollectionAdapter(collectionsList, onCollectionSelectedListener!!)
            binding.fragmentSacadorCollections.layoutManager = lm
            binding.fragmentSacadorCollections.adapter = adapter

        }

        private fun addCollectionToList(collection: String) {
            var isNew = true
            collectionsList.forEach {
                if (it.collectionFk == collection) {
                    isNew = false
                }
            }
            if (isNew) {
                collectionsList.add(CollectionVO(collectionFk = collection, created = getString(R.string.newCreated)))
                adapter?.notifyDataSetChanged()
            } else {
                customDialog.setTitle(getString(R.string.info))
                    .setDescription(getString(R.string.collectionPending) + collection)
                    .setOkButton(getString(R.string.accept)) {
                        customDialog.dismiss()
                    }.show()
            }
            //sergio:para asegurarnos que se actualiza pantalla.
            adapter?.notifyDataSetChanged()
        }



    }
