package de.sebse.fuplanner2.auth

import android.accounts.Account
import android.accounts.AccountAuthenticatorResponse
import android.accounts.AccountManager
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import de.sebse.fuplanner2.R
import de.sebse.fuplanner2.utils.console
import kotlinx.coroutines.*


class FuplannerAccountActivity : AccountAuthenticatorAppCompatActivity() {
    private val REQ_REGISTER = 11
    override fun onCreate(icicle: Bundle?) {
        super.onCreate(icicle)
        setContentView(R.layout.activity_login)

    }

    @Suppress("UNUSED_PARAMETER")
    fun login(view: View?) {
        val userId =
            (findViewById<View>(R.id.user) as EditText).text.toString()
        val passWd =
            (findViewById<View>(R.id.password) as EditText).text.toString()
        findViewById<View>(R.id.login).isEnabled = false

        val accountType = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)

        val result = Intent()
        GlobalScope.async {
            // Check if account is already added
            val accounts = AppAccounts.getInstance()
            if (accounts.hasAccountName(userId, accountType)) {
                throw IllegalArgumentException("Account already bound!")
            }

            val authToken = FuplannerAccountHelper.authenticate(applicationContext, userId, passWd, addNewUser = intent.getBooleanExtra(FuplannerAccountConstants.KEY_ADD_ACCOUNT, false))
            val tokenType: String = FuplannerAccountHelper.getTokenType(userId)
            val data = Bundle()
            data.putString(AccountManager.KEY_ACCOUNT_NAME, userId)
            data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType)
            data.putString(FuplannerAccountConstants.KEY_AUTH_TOKEN_TYPE, tokenType)
            data.putString(AccountManager.KEY_AUTHTOKEN, authToken)
            data.putString(FuplannerAccountConstants.KEY_PASSWORD, passWd)
            result.putExtras(data)
        }.invokeOnCompletion {
            if (it !== null) {
                console.error("An error occured!", it)
                runOnUiThread {
                    findViewById<EditText>(R.id.user).text.clear()
                    findViewById<EditText>(R.id.user).setText("seedorf96", TextView.BufferType.EDITABLE)
                    findViewById<EditText>(R.id.password).text.clear()
                    findViewById<EditText>(R.id.password).setText("m&gcwBaT@", TextView.BufferType.EDITABLE)
                    findViewById<View>(R.id.login).isEnabled = true
                }
            } else if (!this.isFinishing) {
                this.setLoginResult(result)
            }
        }
    }

    private fun setLoginResult(intent: Intent) {
        val userId = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME)
        val passWd = intent.getStringExtra(FuplannerAccountConstants.KEY_PASSWORD)
        val account = Account(userId, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE))
        val accounts = AppAccounts.getInstance()
        if (getIntent().getBooleanExtra(FuplannerAccountConstants.KEY_ADD_ACCOUNT, false)) {
            val authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN)
            val tokenType =
                intent.getStringExtra(FuplannerAccountConstants.KEY_AUTH_TOKEN_TYPE)
            accounts.addAccountExplicitly(account, passWd, null)
            accounts.setAuthToken(account, tokenType, authtoken)
        } else {
            accounts.setPassword(account, passWd)
        }
        setAccountAuthenticatorResult(intent.extras)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        if (data != null && resultCode == Activity.RESULT_OK && requestCode == REQ_REGISTER) {
            setLoginResult(data)
        } else super.onActivityResult(requestCode, resultCode, data)
    }

    companion object {
        fun createIntent(activityCtx: Context, addAccount: Boolean,
                         accountType: String? = null,
                         accountName: String? = null,
                         response: AccountAuthenticatorResponse? = null,
                         authTokenType: String? = null
        ): Intent {
            return Intent(activityCtx, FuplannerAccountActivity::class.java).run {
                putExtra(FuplannerAccountConstants.KEY_ADD_ACCOUNT, addAccount)
                if (response != null)
                    putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response)
                if (accountName != null)
                    putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName)
                putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType ?: FuplannerAccountConstants.FU_ACC_TYPE)
                putExtra(FuplannerAccountConstants.KEY_AUTH_TOKEN_TYPE, authTokenType ?: FuplannerAccountConstants.FU_ACC_TOKEN_TYPE)
            }
        }
    }
}