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

import android.content.Context
import android.graphics.drawable.Drawable
import android.text.InputType
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentSacadorBinding
import es.verdnatura.domain.ConstAndValues.PREITEMPICKER
import es.verdnatura.domain.ConstAndValues.PRINTERNAME
import es.verdnatura.domain.ConstAndValues.SECTORFK
import es.verdnatura.domain.toast
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.component.CustomDialogInput
import es.verdnatura.presentation.view.feature.sacador.adapter.CollectionAdapter
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: CollectionAdapter? = null
    private lateinit var customDialogInput: CustomDialogInput

    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())
        customDialogInput = CustomDialogInput(requireContext())
        setToolBar()
        setEvents()
        viewModel.sectorCollectionGet()
        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.onMyBackPressed()
        }

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

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


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

                    when (item) {
                        iconAdd.drawable -> {
                            if (mobileApplication.dataStoreApp.readDataStoreKey<Int>(SECTORFK) != -1) {
                                viewModel.sectorCollection_new(
                                    mobileApplication.dataStoreApp.readDataStoreKey(
                                        SECTORFK
                                    )
                                )
                            } else {
                                ma.messageWithSound(
                                    message = getString(R.string.errorSector),
                                    isError = true,
                                    isPlayed = true
                                )
                            }
                        }

                        iconPrint.drawable -> {
                            showPrintPrevious()
                        }
                    }
                }
            })
        binding.mainToolbar.toolbarIcons.layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun print() {
        if (ma.havePrinter()) {
            viewModel.ticketPrintLabelPrevious(customDialogInput.getValue().toInt())
            (getString(R.string.Imprimiendo) + mobileApplication.dataStoreApp.readDataStoreKey<String>(
                PRINTERNAME
            )).toast(
                requireContext()
            )
        } else {
            getString(R.string.selectPrinter).toast(requireContext())
        }
    }

    private fun showPrintPrevious() {

        customDialogInput.setInputText(InputType.TYPE_CLASS_NUMBER)
        customDialogInput.setTitle(getString(R.string.printTicket))
        customDialogInput.setDescription(getString(R.string.printPreviousGroup)).setValue("")
            .setOkButton(getString(R.string.print)) {
                try {
                    if (customDialogInput.getValue().isNotEmpty()) {
                        print()
                    }
                } catch (ex: Exception) {
                    getString(R.string.errorInput).toast(requireContext())
                }
                customDialogInput.setValue("")

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


        customDialogInput.setFocusText()
        ma.hideKeyboard(customDialogInput.getEditText())

        customDialogInput.getEditText().setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0 || actionId == 5) {

                if (customDialogInput.getValue().isNotEmpty()) {
                    print()
                }

                return@setOnEditorActionListener true
            }
            false
        }
    }

    private fun setEvents() {
        binding.sacadorSwipe.setOnRefreshListener {
            viewModel.sectorCollectionGet()
            binding.sacadorSwipe.isRefreshing = false
        }
    }

    override fun observeViewModel() {

        with(viewModel) {

            collectionList.observe(viewLifecycleOwner) {
                if (!goBack2) createCollectionList(it.list)
                goBack2 = false
            }

            response.observe(viewLifecycleOwner) {
                if (goBack) addCollectionToList(it.response.toInt())
                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!!, PREITEMPICKER)
        binding.fragmentSacadorCollections.layoutManager = lm
        binding.fragmentSacadorCollections.adapter = adapter

    }

    private fun addCollectionToList(collection: Int) {
        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()
    }

}
