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

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.os.Build
import android.os.Environment
import android.provider.Settings
import android.util.Log.d
import android.view.View
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.ktx.Firebase
import es.verdnatura.MobileApplication
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.OnTrashItemRowClickListener
import es.verdnatura.presentation.common.OnWorkFormsItemRowClickListener
import es.verdnatura.presentation.view.component.CustomDialog
import es.verdnatura.presentation.view.component.CustomDialogInputThreeValues
import es.verdnatura.presentation.view.component.CustomDialogList
import es.verdnatura.presentation.view.feature.login.adapter.WorkFormAdapter
import es.verdnatura.presentation.view.feature.login.model.WorkForms
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import java.io.File
import java.util.*
import kotlin.system.exitProcess


class LoginFragment(var imageUri: Uri?) :
    BaseFragment<FragmentLoginBinding, LoginViewModel>(LoginViewModel::class) {

    private lateinit var customDialog: CustomDialog
    private lateinit var customNewForm: CustomDialogInputThreeValues
    private var workFormAdapter: WorkFormAdapter? = null
    private lateinit var customDialogList: CustomDialogList
    private lateinit var listForms: List<WorkForms>


    companion object {
        fun newInstance(imageUri: Uri?) = LoginFragment(imageUri)
    }

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

    @RequiresApi(Build.VERSION_CODES.O)
    override fun init() {

        customDialogList = CustomDialogList(requireContext())
        customDialog = CustomDialog(requireContext())
        /*Tarea 4815*/
        createFolderSerial()
        saveIdentifiers()
        checkUser()
        //Tarea 5613
        //viewModel.getAccessTokenConfigs()

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

            )
        }

//Tarea 5613 se quita porque debe hacerse login. Ya no se guarda user y password per
        if (getData(TOKEN).isNotBlank() && binding.switchRemember.isChecked) {
            viewModel.operator_add()
        }

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

        binding.edittextServer.setText(getData(WORKFORMSELECTED))


        if (binding.edittextServer.text.toString() == "TestLOCAL") {
            binding.edittextUsername.setText("developer")
            binding.edittextPassword.setText("nightmare")
        }
        // se crean/listan las opciones de formas de trabajo
        //deleteWorkForm("all")
        listForms = getWorkForm().sortedBy { it.created }


        binding.edittextServer.keyListener = null
        binding.edittextServer.setOnLongClickListener {
            showWorkingForms()
            true
        }
        binding.edittextUsername.requestFocus()

    }

    private fun createFolderSerial() {

        val directory = File(
            requireContext().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS),
            "/dataSerial"
        )

        if (!directory.exists()) {
            directory.mkdirs()
        }
        try {
            val filename = "serial.txt"
            val file = File(directory, filename)
            //saveData("SERIALNUMBER", file.readText())
            mobileApplication.serialNumber = file.readText()
        } catch (ex: Exception) {
            d("VERDNATURA:", getString(R.string.errorFile))
        }

    }

    private fun setAdapter(listWorkForms: List<WorkForms>) {

        workFormAdapter = WorkFormAdapter(listWorkForms, object : OnWorkFormsItemRowClickListener {

            override fun OnWorkFormsItemRowClickListener(item: WorkForms) {

                when (item.name) {
                    "Añadir..." -> {
                        showNewForm()
                    }

                    else -> {
                        binding.edittextServer.setText(item.name)
                        saveData("base_url", item.urlSilex)
                        saveData("base_urlSalix", item.urlSalix)
                        saveData(WORKFORMSELECTED, item.name)
                        customDialogList.dismiss()
                        exitProcess(1)

                    }
                }

            }
        }, object : OnTrashItemRowClickListener {
            override fun OnTrashItemRowClickListener(workForm: WorkForms) {

                customDialog.setTitle(getString(R.string.deleteWorkForm))
                    .setDescription(getString(R.string.deleteWorkFormConfirmation))
                    .setOkButton(getString(R.string.cancel)) {
                        customDialog.dismiss()
                    }
                    .setOkButton(getString(R.string.ok)) {
                        deleteWorkForm(workForm.name)
                        workFormAdapter!!.notifyDataSetChanged()

                        customDialog.dismiss()
                        customDialogList.dismiss()
                        saveData(WORKFORMSELECTED, "Producción")
                        exitProcess(1)


                    }
                    .show()


            }
        })


        customDialogList.getRecyclerView().adapter = workFormAdapter
        customDialogList.getRecyclerView().layoutManager =
            LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)


        customDialogList.setTitle(getString(R.string.selectWorkingForm))
            .hideDescription()
            .hideDialog()
            .setOkButton(getString(R.string.cancel)) {
                customDialogList.dismiss()
            }
            .show()


    }

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

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

    }

    private fun showWorkingForms() {

        listForms = getWorkForm().sortedBy { it.created }
        setAdapter(listForms)

    }

    private fun showNewForm() {
        customNewForm = CustomDialogInputThreeValues(requireContext())
            .setTitle(getString(R.string.workFormAdd))
            .setDescription(getString(R.string.workFormDescrip))
        customNewForm.setInfoTex(
            getString(R.string.name),
            getString(R.string.silexServer),
            getString(R.string.salixServer)
        )
        customNewForm.setFocusText()
        customNewForm.setOkButton(getString(R.string.save)) {
            saveWorkForm(
                WorkForms(
                    customNewForm.getValue(),
                    customNewForm.getValueTwo(),
                    customNewForm.getValueThree(),
                    true
                )
            )

            binding.edittextServer.setText(customNewForm.getValue())
            saveData(WORKFORMSELECTED, customNewForm.getValue())
            customNewForm.dismiss()
            customDialogList.dismiss()
            exitProcess(1)

        }.setKoButton(getString(R.string.cancel)) {
            customNewForm.dismiss()
        }

        customNewForm.show()

    }

    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 (prefs.getString("token", "") != "") {
                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
                                )
                            ) {
                                try {
                                    val openURL = Intent(Intent.ACTION_VIEW)
                                    openURL.data =
                                        Uri.parse(it.url)
                                    startActivity(openURL)
                                } catch (ex: Exception) {
                                    getString(R.string.problemUpdate).toast(requireActivity())
                                }

                            }
                        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
                            }.show()

                    } else {
                        //sergio: se añade el log
                        viewModel.getCurrentUserData(
                            getString(R.string.logAppName),
                            getInfoVersionNameApp(),
                            getData(ANDROID_ID)
                        )

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

                        if (it.vIsAuthorized == "1") {

                            if (it.vMessage.isNullOrEmpty()) {
                                getVersion()
                            } else {
                                customDialog.setTitle(getString(R.string.info))
                                    .setDescription(it.vMessage)
                                    .setOkButton(getString(R.string.close)) {
                                        customDialog.dismiss()
                                        getVersion()
                                    }.show()
                            }

                        }

                    }

                }

            }

          /*  workerId.observe(viewLifecycleOwner) {
                if (!it.isError) {
                    saveUserFkPref(it.Id.toString())
                }
            }*/
            //Tarea 5870
            workerOperator.observe(viewLifecycleOwner) {
                if (it.isError) {
                    customDialog.setTitle(getString(R.string.info))
                        .setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                } else {
                   saveDataOperator(it)

                }
            }
            operatorAdd.observe(viewLifecycleOwner) {

                if (it.isError) {
                    customDialog.setTitle(getString(R.string.info))
                        .setDescription(it.errorMessage)
                        .setOkButton(getString(R.string.close)) {
                            customDialog.dismiss()
                        }.show()
                }

                viewModel.device_checkLogin(
                    getData(ANDROID_ID)
                )
                //  viewModel.operator_getNumberOfWagons()
            }

           /* 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 ->

                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[0].id)
                            saveData(PRINTERNAME, it.list[0].name)
                        } else {
                            it.list.get(0).errorMessage.toast(context)
                        }
                    }
                }

            })*/


            loginSalixItem.observe(viewLifecycleOwner) {

                if (it.isError) {
                    binding.splashProgress.visibility = View.GONE
                    saveTokenPref("", 0)
                    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, it.ttl)
                    //test
                    //saveTokenPref("RTymwJzRuVchAMY5u8xG2wpgcjPf7t0DQImLvMsTdNFmbFwDiVsa8lA6fr1XSaBo","2026-29-06")
                    // local
                    //saveTokenPref("1ZGV1OGhpcrZZwvNALXnPeSVe0GCE4tgpKbv8nZu4EXay75QZrVY5GZDnpsqlxFz",it.ttl )
                    //Tarea 5613 borrar que se guarde
                    /* saveUserAccesPref(
                         binding.edittextUsername.text.toString(),
                         binding.edittextPassword.text.toString()
                     )*/
                    app.userName = binding.edittextUsername.text.toString()
                    app.userPassword = binding.edittextPassword.text.toString()

                    //Tarea 5613
                    viewModel.getAccessTokenConfigs()
                    //viewModel.operator_add()

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

                event.getContentIfNotHandled().notNull {

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

                    } else {
                        if (!it.list[0].isError) {
                            saveDataLong("renewPeriod", it.list[0].renewPeriod)
                            saveDataLong("renewInterval", it.list[0].renewInterval)
                            viewModel.operator_add()
                        } else {
                            it.list[0].errorMessage.toast(context)
                        }
                    }
                }

            })

        }
        super.observeViewModel()
    }

    private fun setupFirebase(userName: String) {
        Firebase.crashlytics.setUserId(userName)
    }

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

    private fun saveTokenPref(token: String, ttl: Long) {
        val prefs: SharedPreferences = requireActivity().getSharedPreferences(PREFS_USER, 0)
        val editor = prefs.edit()
        editor.putString(TOKEN, token)
        editor.putLong(TTL, ttl)
        editor.putLong(TOKENCREATED, Date().time)
        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() {
        setupFirebase((requireActivity().application as MobileApplication).userName.toString())
        val intent = Intent(activity, MainActivity::class.java)
        intent.data = imageUri
        startActivity(intent)
        binding.splashProgress.visibility = View.GONE
        requireActivity().finish()
    }

    private fun getVersion() {
        binding.splashProgress.visibility = View.VISIBLE
        viewModel.checkVersion(
            nameApp = getString(R.string.nameApp)

        )

    }

}

