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


import android.annotation.SuppressLint
import android.content.Context
import android.graphics.drawable.Drawable
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentExpeditionTruckListBinding
import es.verdnatura.domain.notNull
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.OnTruckClickListener
import es.verdnatura.presentation.view.component.CustomDialogHour
import es.verdnatura.presentation.view.feature.inventario.adapter.ToolBarAdapter
import es.verdnatura.presentation.view.feature.paletizador.adapter.ExpeditionListAdapter
import es.verdnatura.presentation.view.feature.paletizador.model.ItemExpeditionTruckList
import java.text.SimpleDateFormat
import java.util.*
import java.util.Calendar.getInstance as getInstance1


@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class ExpeditionTruckListFragment  : BaseFragment<FragmentExpeditionTruckListBinding, ExpeditionTruckListViewModel>(
    ExpeditionTruckListViewModel::class) {

    private var adapter : ExpeditionListAdapter? = null
    private lateinit var customDialogHor: CustomDialogHour
    private var onTruckClickListener: OnTruckClickListener? = null


    companion object {//similar a static en Java
        fun newInstance() = ExpeditionTruckListFragment()
    }

    override fun onAttach(context: Context) {
        if (context is OnTruckClickListener) onTruckClickListener = context
        super.onAttach(context)
    }

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

    @SuppressLint("SetTextI18n")
    override fun init() {
        customDialogHor = CustomDialogHour(requireContext())
        binding.splashProgress.visibility = View.VISIBLE
        binding.mainToolbar.toolbarTitle.text = getString(R.string.psScan)+getCURDATE()
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }

        setToolBar()

        viewModel.expeditionTruckList(getData(USER),
            getData(PASSWORD))
        super.init()
    }

    private fun setToolBar(){
        val listIcons:ArrayList<Drawable> = ArrayList()
        val iconReload : Drawable = resources.getDrawable(R.drawable.ic_autorenew_black_24dp,resources.newTheme())
        val iconPlus : Drawable = resources.getDrawable(R.drawable.ic_add_black_24dp,resources.newTheme())
        val iconState : Drawable = resources.getDrawable(R.drawable.ic_visibility_white_24dp,resources.newTheme())

        listIcons.add(iconState)
        listIcons.add(iconReload)
        listIcons.add(iconPlus)


        binding.mainToolbar.toolbarIcons.adapter = ToolBarAdapter(listIcons,object: OnOptionsSelectedListener {
            override fun onOptionsItemSelected(item: Drawable) {
                if (item == iconReload){
                    binding.splashProgress.visibility = View.VISIBLE
                    viewModel.expeditionTruckList(getData(USER),
                        getData(PASSWORD))
                }else if(item == iconPlus){
                    addTruck()
                }
                if (item == iconState){
                    ma.openFragmentExpeditionState()
                }
            }
        })
        binding.mainToolbar.toolbarIcons.layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
    }

    private fun getCURDATE():String{
        val c: Date = getInstance1().getTime()
        val df = SimpleDateFormat(getString(R.string.dayFormat))
        return df.format(c)
    }

    override fun observeViewModel() {
        with(viewModel){
            loadExpeditionTruckList.observe(viewLifecycleOwner, Observer { event ->
                event.getContentIfNotHandled().notNull {printExpeditionList(it) }
            })
            loadResponseExpeditionAdd.observe(viewLifecycleOwner, Observer { event ->
                viewModel.expeditionTruckList(getData(USER),
                    getData(PASSWORD))
            })
        }
    }

    private fun printExpeditionList(it: ItemExpeditionTruckList){
        binding.splashProgress.visibility = View.GONE
        val lm = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
       // Tarea#4125  Refactor Destino por description
        for (itemExp in it.list){
            if (itemExp.description.isNullOrEmpty()){
                itemExp.description=itemExp.Destino
            }
        }
        adapter = ExpeditionListAdapter(it.list,onTruckClickListener!!)
        binding.expeditionTruckRecyclerview.adapter = adapter
        binding.expeditionTruckRecyclerview.layoutManager = lm
        ////Log.i("VERDNATURA:","2-Rellenamos adapter")
    }

    private fun addTruck(){
        customDialogHor.setTitle(getString(R.string.newTruck)).setOkButton(getString(R.string.save)){
            ma.hideKeyboard(customDialogHor.getDestinoEditText())
            if (customDialogHor.getDestinoValue().isNotEmpty() && customDialogHor.getHoraValue().isNotEmpty()){
                viewModel.expeditionTruckAdd(getData(USER),
                    getData(PASSWORD),customDialogHor.getHoraValue(),customDialogHor.getDestinoValue())
                binding.splashProgress.visibility = View.VISIBLE
                customDialogHor.dismiss()
            }
            ma.hideKeyboard(customDialogHor.getDestinoEditText())
            customDialogHor.dismiss()
        }.setKoButton(getString(R.string.cancel)){
            customDialogHor.dismiss()
        }.setHoraValue("").setDestinoValue("").show()

        customDialogHor.getDestinoEditText().requestFocus()
        customDialogHor.getDestinoEditText().setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_DONE || actionId == 0) {
                if (customDialogHor.getDestinoValue().isNotEmpty() && customDialogHor.getHoraValue()
                        .isNotEmpty()){
                    viewModel.expeditionTruckAdd(getData(USER),
                        getData(PASSWORD),customDialogHor.getHoraValue(),customDialogHor.getDestinoValue())
                    binding.splashProgress.visibility = View.VISIBLE
                    customDialogHor.dismiss()
                }

                return@setOnEditorActionListener true
            }
            ma.hideKeyboard(customDialogHor.getDestinoEditText())
            false
        }
    }




}











