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

import android.content.Intent
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Build
import android.view.View.*
import android.widget.ImageView
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import es.verdnatura.R
import es.verdnatura.databinding.FragmentVehiclecontrolUserBinding
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.OnOptionsSelectedListener
import es.verdnatura.presentation.common.ToolBarAdapterTooltip
import es.verdnatura.presentation.common.loadUrl


class ControlVehiculoUsuarioFragment(
    var vUserFK: Int
) : BaseFragment<FragmentVehiclecontrolUserBinding, ControlVehiculoViewModel>(
    ControlVehiculoViewModel::class
) {

    private var userFk = 0
    private var goBack: Boolean = false
    override fun getLayoutId(): Int = R.layout.fragment_vehiclecontrol_user


    companion object {
        fun newInstance(vUserFK: Int) = ControlVehiculoUsuarioFragment(vUserFK)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {
        binding.mainToolbar.toolbarTitle.text = getString(R.string.vehiclecontroluser)
        goBack = false
        binding.splashProgress.visibility = GONE
        setEvents()
        setToolBar()
        setControlVehicleUser()
        super.init()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun setToolBar() {

        binding.mainToolbar.toolbarSubtitle.visibility = VISIBLE
        binding.mainToolbar.toolbarIcons.visibility = VISIBLE
        binding.mainToolbar.backButton.visibility = VISIBLE

        val listIcons: ArrayList<ImageView> = ArrayList()
        val iconPhone = ImageView(context)
        iconPhone.setImageResource(R.drawable.phone_call)

        iconPhone.tooltipText = getTooltip(R.drawable.phone_call)
        listIcons.add(iconPhone)
        binding.mainToolbar.toolbarIcons.adapter =
            ToolBarAdapterTooltip(listIcons, object : OnOptionsSelectedListener {
                override fun onOptionsItemSelected(item: Drawable) {

                    when (item) {
                        iconPhone.drawable -> getExtensionFromUser()

                    }

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

    private fun getExtensionFromUser() {

        binding.splashProgress.visibility = VISIBLE
        viewModel.sip_getExtensionSalix(vUserFK)
    }

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

    private fun setControlVehicleUser() {

        userFk = mobileApplication.userId!!

        if (userFk == vUserFK.toInt()) {
            binding.splashProgress.visibility = VISIBLE
            viewModel.machine_getWorkerPlate()
            viewModel.deviceProduction_getnameDevice(
                getData(ANDROID_ID)
            )
            viewModel.deviceProductionUser_getWorker(
                getData(ANDROID_ID)
            )

        } else {
            userFk = vUserFK.toInt()
            binding.userInformation.visibility = INVISIBLE
            binding.nameVehiclecontrol.visibility = INVISIBLE
            binding.userImage.setOnClickListener { binding.mainToolbar.backButton.performClick() }
            viewModel.machine_getWorkerPlate()
        }

        binding.userImage.loadUrl(
            getData("base_urlSalix") + "/api/Images/user/160x160/$userFk/download?access_token=${
                getData(
                    TOKEN
                )
            }"
        )
        binding.nameVehiclecontrol.text = mobileApplication.userName
        binding.registeredVehiclecontrol.text = ""
        binding.deviceName.text = ""
        binding.assignedDevicename.text = ""

    }

    private fun setEvents() {
        binding.mainToolbar.backButton.setOnClickListener {
            requireActivity().onBackPressed()
        }


    }


    override fun observeViewModel() {

        with(viewModel) {
            binding.splashProgress.visibility = GONE


            responsemachine.observe(viewLifecycleOwner, Observer {
                binding.splashProgress.visibility = GONE
                if (it.isError) {
                    ma.messageWithSound(it.errorMessage, true, false)

                } else {


                    if (it.response == "false") {
                        if (it.type.equals("getWorker")) {
                            binding.assignedDevicename.text =
                                getString(R.string.noAssigned)
                        }
                    } else {

                        when (it.type) {
                            "getnameDevice" -> binding.deviceName.text = it.response
                            "getWorker" -> binding.assignedDevicename.text =
                                it.response
                            "getWorkerPlate" -> binding.registeredVehiclecontrol.text = it.response
                        }

                    }

                }

            })
            responseGetExtensionFromUserId.observe(viewLifecycleOwner, Observer {

                binding.splashProgress.visibility = GONE

                if (it.isError) {
                    ma.messageWithSound(
                        getString(R.string.noSIP) + it.errorMessage + getString(R.string.user) + vUserFK,
                        isError = true,
                        true
                    )

                } else {

                    callPicker(it.response)
                }

            })

        }

    }

    private fun callPicker(extensionNumber: String) {


        try {
            val intent = Intent(Intent.ACTION_DIAL).apply {
                data = Uri.parse("tel:$extensionNumber")
            }

            startActivity(intent)
        } catch (e: Exception) {

        }


    }
}
