package com.seatel.mobilehall.ui.login.presenter

import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Build
import android.widget.ImageView
import com.seatel.mobilehall.ui.login.interactor.FingerprintInteractor
import com.seatel.mobilehall.util.FingerprintSystemManager
import com.seatel.mobilehall.util.FingerprintUiHelper

class FingerprintPresenter(
    var context: Context,
    identify: String,
    imgLogo: ImageView,
    messageError: String,
    var view: FingerprintInteractor.View
) : FingerprintUiHelper.Callback {

    private var mFingerprintUiHelper: FingerprintUiHelper? = null

    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mFingerprintUiHelper = FingerprintUiHelper(
                context, identify,
                context.getSystemService(FingerprintManager::class.java),
                imgLogo, messageError, this
            )
        }

    }

    override fun onAuthenticated() {
        view.onSuccessAuthenticated()
    }

    override fun onError() {
        view.onErrorAuthenticated()
        stopListenFingerprint()
    }

    fun startListenFingerprint() {
        FingerprintSystemManager.getAndroidKeyStore()

        val defaultCipher = FingerprintSystemManager.getCipher()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            FingerprintSystemManager.getSystemService(context)
            if (FingerprintSystemManager.initCipher(defaultCipher!!, "default_key")) {

                if (!mFingerprintUiHelper!!.isFingerprintAuthAvailable) {
                    //hideLogoFingerprint()
                }
                mFingerprintUiHelper?.startListening(FingerprintManager.CryptoObject(defaultCipher))
                view.onShowLogoFingerprint()

            } else {
                view.onHideLogoFingerprint()
            }
        } else {
            view.onHideLogoFingerprint()
        }
    }

    fun stopListenFingerprint() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mFingerprintUiHelper?.stopListening()
        }

    }


}
