package com.dlc.eboard.ui.auth.fragment

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import com.dlc.eboard.databinding.FragmentAuthFingerBinding
import com.dlc.eboard.finger.FingerHelper
import com.dlc.eboard.finger.OnFingerListener
import com.dlc.eboard.ui.auth.AuthType
import com.dlc.eboard.ui.auth.OnAuthResultListener
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.httpcore.vo.response.UserFingerVo

/**
 * 指纹验证
 *
 * @author ReiChin_
 */
class FingerAuthFragment :
    RcBaseFragment<FragmentAuthFingerBinding>() {

    companion object {
        const val TAG = "FingerAuthFragment"

        fun newInstance() = FingerAuthFragment()
    }

    private lateinit var mFingerHelper: FingerHelper

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentAuthFingerBinding {
        return FragmentAuthFingerBinding.inflate(inflater, container, false)
    }

    override fun initViews(savedInstanceState: Bundle?) {
    }

    private fun generateFingerHelper(): FingerHelper {
        return FingerHelper(object : OnFingerListener {
            override fun showToast(message: String) {
                if (!isResumed) return
                this@FingerAuthFragment.showToast(message)
                if ("设备忙" == message) {
                    viewBinding.tipImage.postDelayed({
                        if (isResumed) mFingerHelper.verify()
                    }, 1000)
                }
            }

            override fun onMatchSuccess(userVo: UserFingerVo): Boolean {
                if (!isResumed) return false
                val activity = requireActivity()
                if (activity is OnAuthResultListener) {
                    activity.onAuthSuccess(AuthType.FINGER, userVo)
                }
                return false
            }

            override fun onMatchFailure(message: String) {
                if (!isResumed) return
                showMatchErrDialog(message)
            }

            override fun loopMatch() {
                if (isResumed) mFingerHelper.verify()
            }
        })
    }

    private fun showMatchErrDialog(message: String) {
        AlertDialog.Builder(requireContext())
            .setTitle("提示")
            .setMessage(message)
            .setCancelable(false)
            .setPositiveButton("重新验证") { _, _ ->
                mFingerHelper.verify()
            }.show()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mFingerHelper = generateFingerHelper()
        lifecycle.addObserver(mFingerHelper)
    }

    override fun onDestroy() {
        super.onDestroy()
        lifecycle.removeObserver(mFingerHelper)
    }

    override fun onResume() {
        super.onResume()
        // 5s后开始验证指纹
        viewBinding.tipImage.postDelayed({
            mFingerHelper.lazyVerify()
        }, 1000)
    }

}