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

import android.app.AlertDialog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context.CLIPBOARD_SERVICE
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.widget.TooltipCompat.setTooltipText
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentAjustesBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnAjustesItemClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.ajustes.adapter.AjustesAdapter
import es.verdnatura.presentation.view.feature.ajustes.model.AjustesItemVO
import es.verdnatura.presentation.view.feature.ajustes.model.Printers
import es.verdnatura.presentation.view.feature.ajustes.model.SectorItemVO
import es.verdnatura.presentation.view.feature.ajustes.model.Train
import es.verdnatura.presentation.view.feature.articulo.model.ItemPackingType
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO

class AjustesFragment :
    BaseFragment<FragmentAjustesBinding, AjustesViewModel>(AjustesViewModel::class) {

    private lateinit var customDialog: CustomDialog
    private var sectorListVO: List<SectorItemVO> = listOf()
    private var printersList: List<Printers> = listOf()
    private var trainsList: List<Train> = listOf()
    private var prefs: SharedPreferences? = null
    private var ajustesAdapter: AjustesAdapter? = null
    private var isWorkerAllowed:Boolean=false
    private var itemPackingList: List<ItemPackingType> = listOf()

    //añadido
    private var wagonList: List<String> = listOf()
    private var tagsList: List<String> = listOf()

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

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


    override fun onCreate(savedInstanceState: Bundle?) {
        prefs = requireActivity().getSharedPreferences(PREFS_USER, 0)
        customDialog = CustomDialog(requireContext())

        super.onCreate(savedInstanceState)

    }


    override fun init() {

        binding.mainToolbar.toolbarTitle.text = getString(R.string.settings)
        binding.splashProgress.visibility=View.VISIBLE
        hideBackButton(binding.mainToolbar)
        viewModel.worker_isF11Allowed(getData(USER), getData(PASSWORD))


        binding.userText.setText(getData(USER))
        val versionName = requireActivity().packageManager.getPackageInfo(
            requireActivity().packageName,
            0
        ).versionName!!
        binding.itemVersion.setText(versionName)

        binding.androididText.setText(
            getData(ANDROID_ID)
        )
        binding.txtserver.setText(getData(getString(R.string.baseurl)))
        super.init()

        setEvents()

    }

    fun setEvents() {
        binding.androididText.setOnClickListener { copyanddrag(binding.androididText.text.toString()) }
        binding.androididText.setOnLongClickListener { copyanddrag(binding.androididText.text.toString()) }


    }


    override fun observeViewModel() {
        with(viewModel) {
            ajustesAdapter = AjustesAdapter(ajustesitem, object : OnAjustesItemClickListener {
                override fun onAjustesItemClickListener(item: AjustesItemVO) {

                      if (item.action) {

                          if (item.id == 0) {
                              binding.splashProgress.visibility = View.VISIBLE
                              // viewModel.getSectors(getData(USER),getData(PASSWORD))
                              viewModel.getSectorsSalix(getData(TOKEN))
                          } else if (item.id == 5) {
                              requireActivity().onBackPressed()
                          } else if (item.id == 1) {
                              //Tarea 4351 quitar parte de mostrar los carros y quitar del layout el ">" del final

                              ma.messageWithSound("El número de carros ahora solo se puede modificar por los encargados", true, true,"Información",false)
                              /* val listCarros: ArrayList<String> = ArrayList()
                               listCarros.add("1")
                               listCarros.add("2")
                               listCarros.add("3")
                               listCarros.add("4")
                               listCarros.add("5")
                               listCarros.add("6")
                               wagonList = listCarros

                               val array = arrayOfNulls<String>(listCarros.size)

                               showDialogCarros(array = listCarros.toArray(array))*/

                          } else if (item.id == 2) {
                              viewModel.printer_get(getData(USER), getData(PASSWORD))

                          } else if (item.id == 3) {
                              val listTagsType: ArrayList<String> = ArrayList()
                              listTagsType.add(getString(R.string.stickers))
                              // listTagsType.add(getString(R.string.smarttags))
                              tagsList = listTagsType
                              val array = arrayOfNulls<String>(listTagsType.size)
                              showItemPickerType(array = listTagsType.toArray(array))
                          } else if (item.id == 4) {
                              ma.onPasillerosItemClickListener(
                                  PasillerosItemVO(
                                      title = getString(R.string.titleUserControlVehicle)
                                  ), getData(USERFK)
                              )

                          }else if (item.id==6){
                              viewModel.train_get(getData(USER), getData(PASSWORD))
                          }else if (item.id==7){
                              viewModel.getItemPackingTypeSalix(getData(TOKEN))
                          }
                      }

                }
            })

            operatorGetNumberOfWagons.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    saveDataInt(NUMBEROFWAGONS, it.response!!)

                }
                setSettings(isWorkerAllowed)
            }

            operatorGetTrainResponse.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    saveData(TRAINNAME, it.response!!)

                }
                setSettings(isWorkerAllowed)
            }

            operatorGetItemPackingType.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    saveData(ITEMPACKING, it.response!!)

                }
                setSettings(isWorkerAllowed)
            }

            workerAllowedResponse.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE
                viewModel.operator_getNumberOfWagons(getData(USER), getData(PASSWORD))
                viewModel.operator_getTrain(getData(USER), getData(PASSWORD))
                viewModel.operator_getItemPackingType(getData(USER), getData(PASSWORD))
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, it.isError, true)

                } else {
                    isWorkerAllowed=it.response.toBoolean()

                }
                setSettings(isWorkerAllowed)
            }

            actionUpdate.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                ma.messageWithSound(
                    if (it.isError) it.errorMessage else {
                        getString(R.string.itemUpdated)
                    }, it.isError, false
                )
            }

            workerupdatePrinter.observe(viewLifecycleOwner) {
                binding.splashProgress.visibility = View.GONE

                ma.messageWithSound(
                    if (it.isError) it.errorMessage else {
                        getString(R.string.printerUpdated)
                    }, it.isError, false
                )
            }


            binding.ajustessItems.adapter = ajustesAdapter
            binding.ajustessItems.layoutManager =
                LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)

            loadSectorList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && it.list.get(0).isError) {
                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.list.get(0).errorMessage)
                            .setOkButton(getString(R.string.Close)) {
                                customDialog.dismiss()
                            }.show()
                    } else {

                        if (it.list.size > 0) {
                            val listSectores: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listSectores.add(it.description)
                            }
                            val array = arrayOfNulls<String>(listSectores.size)
                            sectorListVO = it.list
                            showDialogSector(listSectores.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.sectors))
                                .setDescription(getString(R.string.Noexistessectores))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadItemPackingList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && it.list.get(0).isError) {
                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.list.get(0).errorMessage)
                            .setOkButton(getString(R.string.Close)) {
                                customDialog.dismiss()
                            }.show()
                    } else {

                        if (it.list.size > 0) {
                            val listItemsPacking: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listItemsPacking.add(it.description)
                            }
                            val array = arrayOfNulls<String>(listItemsPacking.size)
                            itemPackingList = it.list
                            showDialog(listItemsPacking.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.settingsTitleItemPacking))
                                .setDescription(getString(R.string.NoItemPackingType))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadPrintersList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && it.list.get(0).isError) {
                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.list.get(0).errorMessage)
                            .setOkButton(getString(R.string.Close)) {
                                customDialog.dismiss()
                            }.show()
                    } else {

                        if (it.list.size > 0) {
                            val listPrinters: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listPrinters.add(it.name)
                            }
                            val array = arrayOfNulls<String>(listPrinters.size)
                            printersList = it.list
                            showDialogPrinters(listPrinters.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.printers))
                                .setDescription(getString(R.string.Noprinters))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
            loadTrainList.observe(viewLifecycleOwner) { event ->
                event.getContentIfNotHandled().notNull {
                    binding.splashProgress.visibility = View.INVISIBLE
                    if (it.list.isNotEmpty() && it.list.get(0).isError) {
                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.list.get(0).errorMessage)
                            .setOkButton(getString(R.string.Close)) {
                                customDialog.dismiss()
                            }.show()
                    } else {

                        if (it.list.size > 0) {
                            val listTrain: ArrayList<String> = ArrayList()
                            it.list.forEach {
                                listTrain.add(it.name)
                            }
                            val array = arrayOfNulls<String>(listTrain.size)
                            trainsList = it.list
                            showDialogTrains(listTrain.toArray(array))

                        } else {
                            customDialog.setTitle(getString(R.string.printers))
                                .setDescription(getString(R.string.Noprinters))
                                .setOkButton(getString(R.string.Close)) {
                                    customDialog.dismiss()
                                }.show()
                        }

                    }
                }
            }
        }
        super.observeViewModel()
    }

    private fun setSettings(actionIsAllowed:Boolean=false) {

        viewModel.inititializeDefaultAjusts(
            getData(SECTORDESCRIP),
            getData(SECTORFK).toInt(),
            getData(WAREHOUSEFK).toInt(),
            getData(NUMBEROFWAGONS),
            getData(TAGSTYPE),
            getData(PRINTERFK).toInt(),
            getData(PRINTERNAME),
            getData(TRAINNAME),
            getData(ITEMPACKING),
            actionIsAllowed = actionIsAllowed

            )
    }

    private fun showDialogPrinters(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.Selecccionaimpresoara))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            printersList.forEach {
                if (it.name.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(PRINTERNAME, it.name)
                    editor.putInt(PRINTERFK, it.id!!)
                    editor.apply()

                    viewModel.ajustesitem.get(2).selected = it.name
                    viewModel.worker_updatePrinter(
                        getData(USER),
                        getData(PASSWORD),
                        it.id.toString()
                    )
                    ajustesAdapter!!.notifyDataSetChanged()
                    ajustesAdapter


                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogTrains(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.selectTrain))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            trainsList.forEach {
                if (it.name.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(TRAINNAME, it.name)
                    editor.putInt(TRAINFK, it.id!!)
                    editor.apply()

                    viewModel.ajustesitem[3].selected = it.name
                    viewModel.operator_updateTrain(
                        getData(USER),
                        getData(PASSWORD),
                        it.id.toString()
                    )
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }
    private fun showDialogSector(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.Seleccionaunsector))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            sectorListVO.forEach {
                if (it.description.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(SECTORDESCRIP, it.description)
                    editor.putInt(SECTORFK, it.id)
                    it.warehouseFk?.let { it1 -> editor.putInt(WAREHOUSEFK, it1) }
                    editor.apply()

                    viewModel.ajustesitem.get(0).sectorFk = it.id
                    viewModel.ajustesitem.get(0).warehouse = it.warehouseFk
                    viewModel.ajustesitem.get(0).selected = it.description
                    viewModel.worker_updateSector(
                        getData(USER),
                        getData(PASSWORD),
                        it.id.toString()
                    )
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialog(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.settingsTitleItemPacking))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            itemPackingList.forEach {
                if (it.description.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(ITEMPACKING, it.description)
                    editor.apply()
                    viewModel.ajustesitem[4].selected = it.description
                    viewModel.operator_updateItemPackingType(
                        getData(USER),
                        getData(PASSWORD),
                        it.code
                    )
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }

        }
        val dialog = builder.create()
        dialog.show()
    }

    private fun showDialogCarros(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)
        builder.setTitle(getString(R.string.Seleccionauncarro))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            wagonList.forEach {
                if (it.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putInt(WAGON, it.toInt())
                    editor.apply()

                    viewModel.ajustesitem.get(1).selected = it
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }


        }

        val dialog = builder.create()
        dialog.show()
    }

    private fun showItemPickerType(array: Array<String>) {
        val builder = AlertDialog.Builder(this.context)


        builder.setTitle(getString(R.string.typeTags))
        builder.setItems(array) { _, which ->
            val selected = array[which]
            tagsList.forEach {
                if (it.equals(selected)) {
                    val editor = prefs!!.edit()
                    editor.putString(TAGSTYPE, it)
                    editor.apply()

                    viewModel.ajustesitem.get(3).selected = it
                    ajustesAdapter!!.notifyDataSetChanged()

                    return@forEach
                }
            }


        }

        val dialog = builder.create()
        dialog.show()
    }


    /*  fun setDefaults(key: String?, value: String?, context: Context?) {
          val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
          val editor = preferences.edit()
          editor.putString(key, value)
          editor.commit()
      }*/

    /* private fun getDefaults(key: String?, context: Context?): String? {
         val preferences = PreferenceManager.getDefaultSharedPreferences(context)
         return preferences.getString(key, null)
     }*/


    private fun copyanddrag(string: String): Boolean {
        val clipboard = getActivity()?.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
        val clip: ClipData = ClipData.newPlainText(getString(R.string.androidid), string)
        clipboard.setPrimaryClip(clip)
        setTooltipText(binding.androididText, getString(R.string.copied))
        return false

    }

}
