package org.libre.agosto.p2play

import android.content.Intent
import android.content.SharedPreferences
import android.os.AsyncTask
import android.os.Bundle
import android.os.Looper
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import org.libre.agosto.p2play.ajax.Auth
import org.libre.agosto.p2play.databinding.ActivityLoginBinding

class LoginActivity : AppCompatActivity() {
    private val auth = Auth()
    lateinit var settings: SharedPreferences
    lateinit var clientId: String
    lateinit var clientSecret: String
    private lateinit var db: Database
    private var optCode: String? = null

    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        setTitle(R.string.action_login)
        db = Database(this)

        settings = PreferenceManager.getDefaultSharedPreferences(this)
        clientId = settings.getString("client_id", "")!!
        clientSecret = settings.getString("client_secret", "")!!

        binding.registerActionBtn.setOnClickListener { startActivity(Intent(this, RegisterActivity::class.java)) }
        binding.loginBtn.setOnClickListener { tryLogin() }
    }

    fun tryLogin() {
        binding.loginBtn.isEnabled = false
        val username = binding.userText.text.toString()
        val password = binding.passwordText.text.toString()

        AsyncTask.execute {
            if (Looper.myLooper() == null) {
                Looper.prepare()
            }

            val token = auth.login(username, password, clientId, clientSecret, optCode)

            // Log.d("token", token.token )
            // Log.d("status", token.status.toString() )

            when (token.status.toString()) {
                "1" -> {
                    db.newToken(token)
                    ManagerSingleton.token = token
                    getUser()
                }
                "0" -> {
                    runOnUiThread {
                        ManagerSingleton.toast(getString(R.string.loginError_msg), this)
                    }
                }
                "-1" -> {
                    runOnUiThread {
                        binding.loginBtn.isEnabled = true
                        ManagerSingleton.toast(getString(R.string.loginFailed_msg), this)
                    }
                }
                "-2" -> {
                    // TODO: Start 2FA modal
                    runOnUiThread {
                        val builder = AlertDialog.Builder(this, R.style.Widget_Material3_MaterialCalendar_Fullscreen)
                        val dialog = layoutInflater.inflate(R.layout.two_factor_dialog, null)

                        val inputTwoFactor = dialog.findViewById<EditText>(R.id.twoFactorText)

                        builder.setView(dialog)
                            .setTitle(R.string.twoFactorLabel)
                            // Add action buttons
                            .setPositiveButton(R.string.loginBtn) { d, _ ->
                                this.optCode = inputTwoFactor.text.toString()
                                this.tryLogin()
                                d.dismiss()
                            }
                            .setNegativeButton("Cancel") { d, _ ->
                                dialog.run { d.cancel() }
                                binding.loginBtn.isEnabled = true
                            }
                        val alertDialog = builder.create()
                        alertDialog.show()
                    }
                }
            }
        }
    }

    fun getUser() {
        val user = auth.me(ManagerSingleton.token.token)
        if (user.status == 1) {
            db.newUser(user)
            ManagerSingleton.user = user
            runOnUiThread {
                ManagerSingleton.toast(getString(R.string.loginSuccess_msg), this)
                finish()
            }
        } else {
            runOnUiThread {
                ManagerSingleton.toast(getString(R.string.loginError_msg), this)
            }
        }
    }
}
