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

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentPackagingBinding
import es.verdnatura.domain.ConstAndValues.ENTRY
import es.verdnatura.domain.ConstAndValues.ENTRYTYPE
import es.verdnatura.domain.ConstAndValues.SUPPLIERID
import es.verdnatura.domain.ConstAndValues.SUPPLIERNAME
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnPasillerosItemClickListener
import es.verdnatura.presentation.view.feature.inventario.fragment.SearchSupplierModel
import es.verdnatura.presentation.view.feature.packaging.fragment.PackagingViewModel.PackagingViewModel
import es.verdnatura.presentation.view.feature.packaging.model.Supplier
import es.verdnatura.presentation.view.feature.pasillero.model.PasillerosItemVO
import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat
import kotlinx.coroutines.runBlocking
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File

@Suppress("UNUSED_ANONYMOUS_PARAMETER")
class SupplierFragment(
    var entryPoint: String = ""

) : BaseFragment<FragmentPackagingBinding, PackagingViewModel>(
    PackagingViewModel::class
) {

    private var pasillerosItemClickListener: OnPasillerosItemClickListener? = null
    private var layoutManager: LinearLayoutManager? = null
    private var onBack = false
    private val suppliers = ArrayList<SearchSupplierModel>()

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

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

    override fun onAttach(context: Context) {
        if (context is OnPasillerosItemClickListener) pasillerosItemClickListener = context
        super.onAttach(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {

        /*  viewModel.getSuppliers(
          )*/

        val drawableId: Int =
            R.drawable.background_test // Reemplaza "mi_drawable" con el nombre de tu recurso Drawable

        /*  val uri: Uri = Uri.parse(
              ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                      context!!.resources.getResourcePackageName(drawableId) + '/' +
                      context!!.resources.getResourceTypeName(drawableId) + '/' +
                      context!!.resources.getResourceEntryName(drawableId)
          )

          val rutaAbsoluta: String = uri.toString()*/

        val file =
            File("/storage/emulated/0/Android/data/es.verdnatura.sfusion/files/Pictures/test.png")
        val filePart = MultipartBody.Part.createFormData(
            "file",
            file.name,
            RequestBody.create(MediaType.parse("image/png"), file)
        )
        viewModel.entry_uploadPhotoSalix(
            1,
            1,
            442,
            21,
            "1",
            "Example description",
            false,
            file = filePart
        )
        // viewModel.entry_addFromBuy(8,1,100)
        super.onCreate(savedInstanceState)
    }

    override fun onPause() {
        onBack = true
        super.onPause()

    }

    override fun init() {

        binding.filterSupplier.setOnClickListener {
            SimpleSearchDialogCompat(
                context,
                getString(R.string.suppliers),
                getString(R.string.escribirparteNombre),
                null,
                suppliers
            ) { baseSearchDialogCompat, nombre, position ->
                binding.filterSupplier.setText((nombre.getName()))
                binding.radiobuttonTypePackaging.visibility = View.VISIBLE

                runBlocking {
                    mobileApplication.dataStoreApp.editDataStoreKey(SUPPLIERNAME, nombre.getName())
                    mobileApplication.dataStoreApp.editDataStoreKey(
                        SUPPLIERID,
                        nombre.getId() as Int
                    )
                }
                baseSearchDialogCompat.dismiss()
            }.show()
        }

        ma.hideBottomNavigation(View.GONE)
        setToolBar()
        setEvents()

        super.init()
    }

    private fun setToolBar() {
        binding.mainToolbar.toolbarTitle.text = entryPoint
    }

    private fun setEvents() {

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

        binding.radiobuttonTypePackaging.setOnCheckedChangeListener { buttonView, isChecked ->
            when (isChecked) {
                R.id.radioButtonRec -> {
                    runBlocking {
                        mobileApplication.dataStoreApp.editDataStoreKey(
                            ENTRYTYPE,
                            "Rec"
                        )
                    }

                }

                R.id.radioButtonDev -> {
                    runBlocking {
                        mobileApplication.dataStoreApp.editDataStoreKey(
                            ENTRYTYPE,
                            "Dev"
                        )
                    }
                }

            }
            if (!onBack) {

                //viewModel.addFromPackaging(getDataInt("SUPPLIERID"), getData("ENTRYTYPE")=="Rec")

            }
            onBack = false

        }
    }

    override fun observeViewModel() {
        with(viewModel) {
            supplierList.observe(viewLifecycleOwner) {
                createSupplierList(it.list)
            }

            response.observe(viewLifecycleOwner) {
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

                }
            }
            entry.observe(viewLifecycleOwner) {

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

                } else {
                    runBlocking { mobileApplication.dataStoreApp.editDataStoreKey(ENTRY, it.id!!) }
                    ma.onPasillerosItemClickListener(
                        PasillerosItemVO(title = getString(R.string.titlePackagingCount)),
                        getString(R.string.titlePackagingCount)
                    )
                }
            }
        }
    }

    private fun createSupplierList(list: List<Supplier>) {
        suppliers.clear()
        list.forEach { supplier ->
            if (!supplier.isError) {
                try {
                    suppliers.add(SearchSupplierModel(supplier.name, supplier.id.toString()))
                } catch (e: Exception) {
                }
            }
        }
    }

}

