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

import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Build
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.setFragmentResultListener
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorBinding
import es.verdnatura.domain.ConstAndValues.SACADOR
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.*
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.sacador.adapter.CollectionAdapter
import es.verdnatura.presentation.view.feature.sacador.model.CollectionVO
import es.verdnatura.presentation.view.feature.smarttag.sacador.fragment.AssociateSmartTagsFragment


private var getCollections = false

class SacadorFragment :
    BaseFragment<FragmentSacadorBinding, SacadorViewModel>(SacadorViewModel::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: CollectionAdapter? = null
    private var resultTagMode: String? = ""


    companion object {
        fun newInstance() = SacadorFragment()
    }

    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
        binding.mainToolbar.toolbarTitle.text = getString(R.string.getcollection)
        setToolBar()
        setEvents()

        if (getCollections) {
            viewModel.collection_new_smart(
                getData(USER),
                getData(PASSWORD),
                getData(SECTORFK),
                getData(WAGON),
                getData(TAGSTYPE)
            )

        } else {
            val working_in_test = true //sergio:  Ok en app
            if (!working_in_test) {
                viewModel.collectionGetSalix(token = getData(TOKEN))
            } else {
                viewModel.collectionGet(
                    getData(USER),
                    getData(PASSWORD)
                )
            }

        }
        super.init()
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setFragmentResultListener("requestKey") { _, bundle ->

            val result = bundle.getString("tagMode")

            resultTagMode = result
            if (result.equals(getString(R.string.complete)) && getData(TAGSTYPE).equals(getString(R.string.smarttags))) {
                getCollections = true

            } else {
                getCollections = false
            }

        }

    }

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

    private fun setToolBar() {

        ma.hideBottomNavigation(View.VISIBLE)

        binding.mainToolbar.backButton.setOnClickListener{
            requireActivity().onBackPressed()
        }

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

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

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

        }

        listIcons.add(iconVehicleIn)
        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
                            // checkTagsMode()
                            //Tarea 4351 cambiar getData(WAGON) por getData(NUMBEROFWAGONS)

                           //Tarea 4130
                            viewModel.collectionNew(
                                getData(USER),
                                getData(PASSWORD),
                                getData(SECTORFK),
                                getData(NUMBEROFWAGONS)
                            )
                           /* viewModel.collection_assign(
                                getData(USER),
                                getData(PASSWORD),
                            )*/

                        }
                        iconVehicleIn.drawable -> ma.onVehicleSelected(SacadorFragment.TAG)
                    }

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

    private fun setEvents() {
        binding.sacadorSwipe.setOnRefreshListener {
            viewModel.collectionGetSalix(token = getData(TOKEN))
            /* viewModel.collectionGet(
                 getData(USER),
                 getData(PASSWORD)
             )*/
            binding.sacadorSwipe.isRefreshing = false
        }
    }


    private fun checkTagsMode() {

        //sergio:codigo smarttags
        //Tarea 4351 cambiar getData(WAGON por NUMBEROFWAGONS)
        if (getData(TAGSTYPE).equals(getString(R.string.stickers))) {
            viewModel.collectionNew(
                getData(USER),
                getData(PASSWORD),
                getData(SECTORFK),
                getData(NUMBEROFWAGONS)
            )
        } else if (getCollections) {

            viewModel.collection_new_smart(
                getData(USER),
                getData(PASSWORD),
                getData(SECTORFK),
                getData(WAGON),
                getData(TAGSTYPE)
            )

        } else {
            requireActivity().addFragment(
                AssociateSmartTagsFragment.newInstance(AssociateSmartTagsFragment.TAG),
                R.id.main_frame_layout,
                AssociateSmartTagsFragment.TAG
            )

        }


    }


    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
            })
            /* collectionTicketList.observe(viewLifecycleOwner, Observer {
                 binding.splashProgress_two.visibility = View.GONE
                 if (it.isError){
                     customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage).setOkButton(getString(R.string.accept)){
                         customDialog.dismiss()
                     }.show()
                 }else{
                     if (!goBack)navigateToCollectionList(it)
                 }
                 goBack = 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.

                val working_in_test = true //sergio: ok en app SACADOR
                if (!working_in_test) {
                    viewModel.collectionGetSalix(token = getData(TOKEN))
                } else {
                    viewModel.collectionGet(getData(USER), getData(PASSWORD))
                }


            })

            responseCollectionSmart.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = View.GONE

                getCollections = false
                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, true, false)

                    } else {

                        viewModel.smartTagInsertTicket(it.response)

                        goBack = false
                    }
                }
            })


            registerSmarttagInsert.observe(viewLifecycleOwner, Observer {

                if (!goBack) {
                    if (it.isError) {
                        ma.messageWithSound(it.errorMessage, true, false)
                        getCollections = true
                    } else {
                        ma.messageWithSound(getString(R.string.ticketInsert), false, false)
                        getCollections = false
                        viewModel.collectionGetSalix(getData(TOKEN))
                    }
                    goBack = false
                }
            })


        }
    }

    private fun createCollectionList(collections: List<CollectionVO>) {
        collectionsList = ArrayList()
        collections.forEach {
            collectionsList.add(it)
        }
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = CollectionAdapter(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()
    }

    private fun navigateToCollectionList(collection: CollectionVO) {
        collectionsList.add(collection)
        adapter?.notifyDataSetChanged()

        onCollectionSelectedListener?.onCollectionSelected(collection, SACADOR)
    }


}
