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

//import es.verdnatura.presentation.view.feature.login.model.LoginItemVO
import android.annotation.SuppressLint
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import androidx.lifecycle.Observer
import es.verdnatura.R
import es.verdnatura.databinding.FragmentLoginBinding
import es.verdnatura.domain.notNull
import es.verdnatura.domain.toast
import es.verdnatura.presentation.base.BaseFragment
import es.verdnatura.presentation.common.hideKeyboard
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import kotlinx.coroutines.*
import java.lang.Boolean.TRUE
import kotlin.system.exitProcess

class LoginFragment : BaseFragment<FragmentLoginBinding, LoginViewModel>(LoginViewModel::class) {

    private lateinit var customDialog: CustomDialog

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

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

    override fun init() {

        customDialog = CustomDialog(requireContext())
        saveIdentifiers()
        checkUser()
        binding.buttonLogin.setOnClickListener {
            binding.splashProgress.visibility = View.VISIBLE
            viewModel.loginSalix(
                user = binding.edittextUsername.text.toString(),
                password = binding.edittextPassword.text.toString()

            )


        }

        binding.textviewRememberPassword.setOnClickListener {
            binding.edittextUsername.setText("")
            binding.edittextPassword.setText("")
            binding.switchRemember.isChecked = false
            saveRemember(false)
        }



        binding.edittextServer.setText(getData(getString(R.string.baseurl)))
        binding.edittextServer.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_UP) {

                saveData(
                    "base_url",
                    binding.edittextServer.text.toString()
                )
                val working_in_test = false
                if (working_in_test) {
                    saveData(
                        "base_urlSalix",
                        "http://localhost:3000/api/"

                    )
                } else {
                    if (binding.edittextServer.text!!.contains("test-app.verdnatura.es")) {
                        saveData(
                            "base_urlSalix",
                            "https://test-salix.verdnatura.es/api/"
                            // "https://test-salix.verdnatura.es/" //localhost desde emulador 10.0.2.2:3000
                            //  "http://localhost:3000/api/"
                            //"http://10.0.2.2:3000/api/" //-> desde emulador 10.0.2.2:3000
                        )

                    } else {
                        saveData(
                            "base_urlSalix",
                            "https://salix.verdnatura.es/api/"
                            /*working_in_test*/
                            //  "http://localhost:3000/api/"
                            //"http://10.0.2.2:3000/api/" //-> desde emulador 10.0.2.2:3000
                        )

                    }
                }

                "${getString(R.string.serverSalix)}${getData("base_urlSalix")})".toast(
                    requireContext()
                )
                this.hideKeyboard()

                CoroutineScope(Dispatchers.IO).launch {
                    delay(2000)
                    withContext(Dispatchers.Main) {
                        exitProcess(0)
                    }
                }


            }
            false
        }


        binding.textviewWelcome.setOnLongClickListener {
            binding.edittextServer.isEnabled = TRUE
            true
        }


    }

    @SuppressLint("HardwareIds")
    private fun saveIdentifiers() {

        val AndroidId: String =
            Settings.Secure.getString(requireActivity().contentResolver, Settings.Secure.ANDROID_ID)
        saveData(ANDROID_ID, AndroidId)

    }

    private fun checkUser() {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        if (prefs.getBoolean(REMEMBER, false)) {
            binding.edittextUsername.setText(prefs.getString(USER, ""))
            binding.edittextPassword.setText(prefs.getString(PASSWORD, ""))
            if (binding.edittextPassword.text.toString().isNotEmpty()) {
                binding.switchRemember.isChecked = true
            }
        }

    }

    override fun observeViewModel() {
        with(viewModel) {

            versionappitem.observe(viewLifecycleOwner) {

                if (it.isError) {
                    binding.splashProgress.visibility = View.GONE
                    customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                } else {

                    if (it.version == getInfoVersionNameApp()) {
                        goToMain()
                    } else {

                        customDialog.setTitle(getString(R.string.Actualizar))
                            .setDescription(getString(R.string.updatemng)).setOkButton(
                                getString(
                                    R.string.Actualizar
                                )
                            ) {
                                val openURL = Intent(Intent.ACTION_VIEW)
                                openURL.data =
                                    Uri.parse(it.url)
                                startActivity(openURL)

                            }
                        if (it.IsVersionCritical == 1) {
                            customDialog.setDescription(getString(R.string.updatecritical))
                        } else {
                            customDialog.setKoButton(getString(R.string.cancel)) {
                                customDialog.dismiss()
                                goToMain()
                            }
                        }
                        customDialog.show()

                    }

                }

            }
            logindevice.observe(viewLifecycleOwner) {

                if (it.isError) {
                    binding.splashProgress.visibility = View.GONE
                    customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                } else {
                    if (it.vIsAuthorized == "0") {

                        customDialog.setTitle(getString(R.string.error))
                            .setDescription(it.vMessage!!)
                            .setOkButton(getString(R.string.close)) {
                                customDialog.dismiss()
                                binding.splashProgress.visibility = View.GONE
                                //  goToMain()
                            }.show()

                    } else {
                        //sergio: se añade el log
                        viewModel.worker_getId(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString()

                        )

                        viewModel.worker_getSector(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString()
                        )


                     /*   viewModel.operator_getNumberOfWagons(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString()
                        )*/

                        viewModel.worker_getPrinter(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString()
                        )



                        deviceLog_add(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString(),
                            getString(R.string.logAppName),
                            getInfoVersionNameApp(),
                            getData(ANDROID_ID)
                        )

                        if (binding.switchRemember.isChecked) {
                            saveRemember(true)
                        } else {
                            saveRemember(false)
                        }

                        saveUserAccesPref(
                            binding.edittextUsername.text.toString(),
                            binding.edittextPassword.text.toString()
                        )


                        if (it.vIsAuthorized == "1" && it.vMessage.isNullOrEmpty()) {

                            getVersion()

                        }
                        if (it.vIsAuthorized == "1" && !it.vMessage.isNullOrEmpty()) {
                            binding.splashProgress.visibility = View.GONE
                            customDialog.setTitle(getString(R.string.info))
                                .setDescription(it.vMessage)
                                .setOkButton(getString(R.string.close)) {
                                    customDialog.dismiss()
                                    /* binding.splashProgress.visibility = View.VISIBLE
                                     loginSalix(
                                         user = binding.edittextUsername.text.toString(),
                                         password = binding.edittextPassword.text.toString(),
                                         "login de Salix"
                                     )*/
                                    getVersion()
                                }.show()

                        }

                    }

                }

            }



            workerId.observe(viewLifecycleOwner) {

                if (!it.isError) {
                    saveUserFkPref(it.Id.toString())
                }


            }
            operatorAdd.observe(viewLifecycleOwner) {

                if (it.isError) {
                    customDialog.setTitle(getString(R.string.info))
                        .setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                }
                    viewModel.operator_getNumberOfWagons(getData(USER),getData(PASSWORD))

                viewModel.device_checkLogin(
                    binding.edittextUsername.text.toString(),
                    binding.edittextPassword.text.toString(),
                    getData(ANDROID_ID)
                )
            }

            operatorGetNumberOfWagons.observe(viewLifecycleOwner) {

                if (!it.isError) {
                    saveDataInt(NUMBEROFWAGONS, it.response!!)
                } else {
                    customDialog.setTitle(getString(R.string.error)).setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                }


            }

            devicelogresponse.observe(viewLifecycleOwner) {

                if (it.isError) {
                    customDialog.setTitle(getString(R.string.error))
                        .setDescription(it.errorMessage)
                        .setOkButton(
                            getString(R.string.accept)
                        ) {
                            customDialog.dismiss()
                            getVersion()
                        }.show()
                }
            }

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


                if (it.isError) {
                    removeSector()
                } else {
                    if (it.id != 0) {
                        saveDataInt(SECTORFK, it.id)
                        saveData(SECTORDESCRIP, it.description)
                        it.warehouseFk?.let { it1 -> saveDataInt(WAREHOUSEFK, it1) }
                    }
                }
            }

            loadWorkerPrintList.observe(viewLifecycleOwner, Observer { event ->
                binding.splashProgress.visibility = View.GONE

                event.getContentIfNotHandled().notNull {

                    if (it.list.isEmpty()) {
                        getString(R.string.selectPrinter).toast(context)
                        removePrinter()

                    } else {
                        if (!it.list.get(0).isError) {
                            saveDataInt(PRINTERFK, it.list.get(0).id!!)
                            saveData(PRINTERNAME, it.list.get(0).name)
                        } else {
                            it.list.get(0).errorMessage.toast(context)
                        }
                    }
                }

            })




            loginsalixitem.observe(viewLifecycleOwner) {

                if (it.isError) {
                    binding.splashProgress.visibility = View.GONE
                    saveTokenPref("")
                    customDialog.setTitle(getString(R.string.error))

                        .setDescription(
                            if (it.errorMessage.contains("Unauthorized")) {
                                getString(R.string.messageUserError)
                            } else {
                                it.errorMessage
                            }
                        )
                        .setOkButton(
                            getString(R.string.accept)
                        ) {
                            customDialog.dismiss()

                        }.show()
                } else {
                    saveTokenPref(it.token)

                    //Tarea 4351 quitar el if y poner e device_checkLogin a continuación del response de operator_add
                        viewModel.operator_add(getData(USER),getData(PASSWORD))

                  /*  viewModel.device_checkLogin(
                        binding.edittextUsername.text.toString(),
                        binding.edittextPassword.text.toString(),
                        getData(ANDROID_ID)
                    )*/

                }
            }

        }
        super.observeViewModel()
    }

    private fun getInfoVersionNameApp(): String {
        val manager: PackageManager = requireContext().packageManager
        val info: PackageInfo = manager.getPackageInfo(requireContext().packageName, 0)
        return info.versionName
    }

    private fun saveTokenPref(token: String) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(TOKEN, token)
        editor.apply()
    }

    /*   private fun saveUserFkPref(loginitem: LoginItemVO) {
           val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
           val editor = prefs.edit()
           editor.putString(USERFK, loginitem.id)
           editor.apply()
       }*/

    private fun saveUserFkPref(workerId: String) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(USERFK, workerId)
        editor.apply()
    }

    private fun saveUserAccesPref(user: String, password: String) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(USER, user)
        editor.putString(PASSWORD, password)
        editor.apply()
    }

    private fun saveRemember(remember: Boolean) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putBoolean(REMEMBER, remember)
        editor.apply()
    }

    private fun goToMain() {
        val intent = Intent(activity, MainActivity::class.java)
        startActivity(intent)
        //binding.splashProgress.visibility=View.GONE
        requireActivity().finish()
    }

    private fun getVersion() {
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.checkVersion(
            user = binding.edittextUsername.text.toString(),
            password = binding.edittextPassword.text.toString(),
            nameApp = getString(R.string.nameApp)

        )

    }

    /*fun setDefaults(key: String?, value: String?, context: Context?) {

        val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
        val editor = preferences.edit()
        editor.putString(key, value)
        editor.commit()
    }*/

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

    // sergio:creada restart en BaseFragment para AjustesFragment...


}
