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.domain.ConstAndValues
import es.verdnatura.domain.ConstAndValues.ANDROID_ID
import es.verdnatura.domain.ConstAndValues.TOKEN
import es.verdnatura.domain.toast
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(
    private 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
        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() {
        viewModel.sip_getExtensionSalix(vUserFK)
    }

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

    private fun setControlVehicleUser() {

        userFk = mobileApplication.userId!!

        if (userFk == vUserFK) {
            var androidId: String = mobileApplication.dataStoreApp.readDataStoreKey(ANDROID_ID)
            viewModel.machineGetWorkerPlate(mobileApplication.userId!!)
            viewModel.deviceProduction_getnameDevice(
                androidId
            )
            viewModel.deviceProductionUserGetWorker(
                androidId
            )
        } else {
            userFk = vUserFK
            binding.userInformation.visibility = INVISIBLE
            binding.nameVehiclecontrol.visibility = INVISIBLE
            binding.userImage.setOnClickListener { binding.mainToolbar.backButton.performClick() }
            viewModel.machineGetWorkerPlate(mobileApplication.userId!!)
        }

        binding.userImage.loadUrl(
            mobileApplication.dataStoreApp.readDataStoreKey<String>(
                ConstAndValues.BASEURLSALIX
            ) + "/api/Images/user/160x160/$userFk/download?access_token=${
                mobileApplication.dataStoreApp.readDataStoreKey<String>(
                    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) {

            responsemachine.observe(viewLifecycleOwner) {

                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 {

                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) {
            getString(R.string.errorOperation).toast(requireContext())
        }

    }
}
