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 kotlinx.android.synthetic.main.activity_register.*
import org.libre.agosto.p2play.ajax.Auth

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        setTitle(R.string.registerActionBtn)

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

        registerBtn.setOnClickListener { registerUser() }
    }

    private fun registerUser() {
        registerBtn.isEnabled = false
        val username = userText2.text.toString()
        val password = passwordText2.text.toString()
        val email = 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)
                }
                registerBtn.isEnabled = true
            }
        }
    }
}
