package com.molette.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.biometric.BiometricPrompt
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.concurrent.Executor

class MainActivity : AppCompatActivity() {

    val executor = Executor{
        GlobalScope.launch(Dispatchers.Main) {
            it.run()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        Log.d("onCreate", "MainActivity")

        toast.setOnClickListener {
            Toast.makeText(this, "This is a toast", Toast.LENGTH_LONG).show()
        }

        showBiometric()
    }

    private fun showBiometric(){

        val prompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback(){
            override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                super.onAuthenticationError(errorCode, errString)
                Log.e("onAuthenticationError", "$errorCode $errString")
                showErrorToast(errorCode, errString)
            }

            override fun onAuthenticationFailed() {
                super.onAuthenticationFailed()
                Log.d("onAuthenticationError", "Failed")
            }

            override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                super.onAuthenticationSucceeded(result)
                Log.d("onAuthenticationSucceeded", "Success")
                showAuthenticationToast()
            }
        })

        val info = BiometricPrompt.PromptInfo.Builder()
            .setDeviceCredentialAllowed(true)
            .setTitle("Biometric")
            //.setNegativeButtonText("Cancel")
            .build()

        prompt.authenticate(info)
    }

    private fun showAuthenticationToast(){
        Toast.makeText(this, "Authentication successful", Toast.LENGTH_LONG).show()
    }

    private fun showErrorToast(errorCode: Int, errorMessage: CharSequence){
        Toast.makeText(this, "$errorCode $errorMessage", Toast.LENGTH_SHORT).show()
    }
}
