package org.wntr.mdeditor


import android.net.Uri
import android.os.Bundle

import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.Toast
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.wntr.mdeditor.MainActivity.Companion.ghostConnection
import org.wntr.mdeditor.databinding.ActivityLoginBinding

import org.wntr.mdeditor.R

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val creds = MainActivity.credManager.loadCredentialsFromSharedPrefs()
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)
        binding.instance.setText(creds.instance)
        binding.username.setText(creds.username)
    }

    fun onButtonLoginClick(view: View) {
        Log.d(javaClass.simpleName,"entered: instance: ${binding.instance.text} username:${binding.username.text}")
        val creds= Credentials(binding.instance.text.toString(), binding.username.text.toString(), binding.password.text.toString())
        registerGhost(creds)
    }

    fun registerGhost(credentials: Credentials){
        if (Uri.parse(credentials.instance).scheme == null) {
            Toast.makeText(
                this@LoginActivity,
                "Scheme wrong. Add https://",
                Toast.LENGTH_SHORT
            ).show()
            MainActivity.credManager.saveCredentialsToSharedPrefs(
                Credentials(
                    "nowhere",
                    credentials.username
                    )
            )
            return
        }
        MainActivity.api = ghostAPI(applicationContext, credentials.instance)
        CoroutineScope(Dispatchers.Main).launch {
            withContext(Dispatchers.IO) {
                var result =""
                try {
                    result = MainActivity.api.register(credentials)
                } catch (e: ExceptionInInitializerError) {
                    this@LoginActivity.runOnUiThread(Runnable() {
                        Toast.makeText(
                            this@LoginActivity,
                            "Probably host name wrong",
                            Toast.LENGTH_SHORT
                        ).show()
                    })
                    Log.i(javaClass.simpleName, "Probably host name wrong")

                    MainActivity.credManager.saveCredentialsToSharedPrefs(
                        Credentials(
                            "nowhere",
                            credentials.username,
                            "nothing"
                        )
                    )
                    finishAffinity()
                } catch (e: NoClassDefFoundError) {
                    this@LoginActivity.runOnUiThread(Runnable() {
                        Toast.makeText(
                            this@LoginActivity,
                            "API client needs restart for setting hostname",
                            Toast.LENGTH_SHORT
                        ).show()
                    })
                    Log.i(javaClass.simpleName, "API client needs restart for setting hostname")
                    finishAffinity()
                }
                when (result) {
                    "PASSWORD_INCORRECT" -> {
                        this@LoginActivity.runOnUiThread(Runnable() {
                            Toast.makeText(
                                this@LoginActivity,
                                "Password Incorrect",
                                Toast.LENGTH_SHORT
                            ).show()
                        })
                        Log.i(javaClass.simpleName, "Password Incorrect")
                        MainActivity.credManager.saveCredentialsToSharedPrefs(
                            Credentials(
                                credentials.instance,
                                credentials.username,
                                "nothing"
                            )
                        )
                    }
                    "404" -> {
                        this@LoginActivity.runOnUiThread(Runnable() {
                            Toast.makeText(
                                this@LoginActivity,
                                "Username nonexistant",
                                Toast.LENGTH_SHORT
                            ).show()
                        })
                        Log.i(javaClass.simpleName,"Username nonexistant")
                        MainActivity.credManager.saveCredentialsToSharedPrefs(
                            Credentials(
                                credentials.instance,
                                "nobody",
                                "nothing"
                            )
                        )
                    }
                    "SUCCESS" -> {
                        MainActivity.credManager.saveCredentialsToSharedPrefs(credentials)
                        ghostConnection = true
                        this@LoginActivity.runOnUiThread(Runnable() {
                            Toast.makeText(
                                this@LoginActivity,
                                "Successfully logged in!",
                                Toast.LENGTH_SHORT
                            ).show()
                        })
                        finish()
                    }

                    else -> {
                        this@LoginActivity.runOnUiThread(Runnable() {
                            Toast.makeText(
                                this@LoginActivity,
                                "Credentials wrong",
                                Toast.LENGTH_SHORT
                            ).show()
                        })
                        Log.i(javaClass.simpleName, "Credentials wrong")
                        MainActivity.credManager.saveCredentialsToSharedPrefs(
                            Credentials(
                                "nowhere",
                                "nobody",
                                "nothing"
                            )
                        )
                    }
                }

            }
        }
    }
}