package org.libre.agosto.p2play

import android.content.SharedPreferences
import android.os.AsyncTask
import android.os.Bundle
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import org.libre.agosto.p2play.ajax.Auth
import org.libre.agosto.p2play.databinding.ActivityRegisterBinding

class RegisterActivity : AppCompatActivity() {
    private val auth = Auth()
    lateinit var settings: SharedPreferences
    lateinit var clientId: String
    lateinit var clientSecret: String

    private lateinit var binding: ActivityRegisterBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        setTitle(R.string.registerActionBtn)

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

        binding.registerBtn.setOnClickListener { registerUser() }
    }

    private fun registerUser() {
        binding.registerBtn.isEnabled = false
        val username = binding.userText2.text.toString()
        val password = binding.passwordText2.text.toString()
        val email = binding.emailText.text.toString()
        AsyncTask.execute {
            if (Looper.myLooper() == null) {
                Looper.prepare()
            }

            val res = auth.register(username, password, email)
            Log.d("Res register", res.toString())
            runOnUiThread {
                when (res) {
                    1 -> {
                        ManagerSingleton.toast(getString(R.string.registerSuccess_msg), this)
                        finish()
                    }
                    0 -> ManagerSingleton.toast(getString(R.string.registerFailed_msg), this)
                    -1 -> ManagerSingleton.toast(getString(R.string.registerError_msg), this)
                }
                binding.registerBtn.isEnabled = true
            }
        }
    }
}
