package com.example.brokenbiometric

import android.os.Build
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
import com.example.brokenbiometric.Keystore.BIOMETRIC
import com.example.brokenbiometric.Keystore.getKeyPair
import com.google.android.gms.tasks.TaskExecutors
import kotlinx.android.synthetic.main.activity_main.*
import java.security.Signature

class MainActivity : AppCompatActivity() {

    private val isSdkVersionSupported = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

    val isFingerprintAvailable = isSdkVersionSupported

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

    override fun onResume() {
        super.onResume()

        authenticateBiometric(this,
            object : BiometricPrompt.AuthenticationCallback() {

                override fun onAuthenticationError(errorCode: Int,
                                                   errString: CharSequence) {

                    if (errorCode != BiometricPrompt.ERROR_CANCELED && errorCode != BiometricPrompt.ERROR_USER_CANCELED) {

                        Toast.makeText(fab.context, "Authentication Error - $errorCode: $errString", Toast.LENGTH_LONG).show()
                    }
                }

                override fun onAuthenticationFailed() {
                    Toast.makeText(fab.context, "Authentication Failed", Toast.LENGTH_LONG).show()

                }

                override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
                    Toast.makeText(fab.context, "Authentication Success", Toast.LENGTH_LONG).show()

                }

            })
    }

    fun authenticateBiometric(activity: FragmentActivity,
                              callback: BiometricPrompt.AuthenticationCallback) {
        var signature: Signature? = null

        try {

            getKeyPair(this, BIOMETRIC)?.let {

                signature = Signature.getInstance("SHA256withECDSA")
                signature?.initSign(it.private)
            }
        } catch (e: Exception) {
            Toast.makeText(fab.context, "Something broke", Toast.LENGTH_LONG).show()
        }

        val promptInfo = BiometricPrompt.PromptInfo.Builder()
            .setTitle(getString(R.string.fingerprint_login))
            .setDescription("")
            .setNegativeButtonText(getString(R.string.cancel))
            .build()


        signature?.let {
            BiometricPrompt(activity, TaskExecutors.MAIN_THREAD, callback).authenticate(
                promptInfo,
                BiometricPrompt.CryptoObject(it)
            )
        }
    }



}
