package com.hx.utils.application.ui.face

import android.Manifest.permission.CAMERA
import android.content.ActivityNotFoundException
import android.content.Intent
import android.graphics.BitmapFactory
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.hx.utils.application.base.BaseFragment
import com.hx.utils.application.databinding.FragmentFaceBinding
import com.izilab.liveness.api.Detector
import com.izilab.liveness.api.LivenessDetectionSDK
import com.izilab.liveness.api.LivenessResult
import com.izilab.liveness.api.SDKConstant
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class FaceFragment : BaseFragment<FragmentFaceBinding, FaceViewModel>() {

    override fun setupViewModel() {
        viewModel = ViewModelProvider(this)[FaceViewModel::class.java]
    }

    override fun setupView() {
        getPermissions()
        LivenessDetectionSDK.enableSDKHandleCameraPermission();
//        binding.fab.setOnClickListener {
//            try {
//                activity?.let {
//                    LivenessDetectionSDK.from(it)
//                        .setActionSequence(
//                            Detector.DetectionType.MOUTH,
//                            Detector.DetectionType.BLINK,
//                            Detector.DetectionType.POS_YAW
//                        )
//                        .setRequestCode(100)
//                        .start()
//                } ?: throw IllegalStateException("Activity is null")
//
//            } catch (e: ActivityNotFoundException) {
//                ToastUtils.showLong("Liveness Activity not found, please check SDK integration.")
//                Log.e("hzshkj", "Liveness SDK Activity is missing", e)
//
//            } catch (e: Exception) {
//                lifecycleScope.launch(Dispatchers.Main) {
//                    delay(2000)
//                    ToastUtils.showLong(e.message ?: "Unknown error")
//                    Log.e("hzshkj", "setupView error: ${e.message}")
//                }
//            }
//        }
        startFace()

    }

    fun startFace(){
        binding.cameraPreview.setLivenessPreviewCallback(object : b.f {
            override fun onLivenessAction(code: Int) {
                when (code) {
                    SDKConstant.CODE_ONLY_ONE_FACE -> {
//                        mGuideTextView.setText(R.string.only_one_face)
                    }
                    SDKConstant.CODE_FACING_CAMERA -> {
//                        mGuideTextView.setText(R.string.facing_camera)
                    }
                    SDKConstant.CODE_OPEN_MOUTH -> {
//                        mGuideTextView.setText(R.string.open_mouth)
                    }
                    SDKConstant.CODE_SHAKE_HEAD -> {
//                        mGuideTextView.setText(R.string.shake_your_head)
                    }
                }
            }

            override fun onLivenessResult(success: Boolean) {
                if(success) {
                    // get front face bitmap
                    val facePhoto = LivenessResult.getFacePhoto()
                    var faceBitmap = facePhoto.bitmap
                    if (faceBitmap == null || faceBitmap.isRecycled) {
                        faceBitmap = BitmapFactory.decodeFile(facePhoto.filePath)
                    }

                    // get mouth bitmap
                    val mouthPhoto = LivenessResult.getMouthPhoto()
                    var mouthBitmap = mouthPhoto.bitmap
                    if (mouthBitmap == null || mouthBitmap.isRecycled) {
                        mouthBitmap = BitmapFactory.decodeFile(mouthPhoto.filePath)
                    }

                    // get blink bitmap
                    val blinkPhoto = LivenessResult.getBlinkPhoto()
                    var blinkBitmap = blinkPhoto.bitmap
                    if (blinkBitmap == null || blinkBitmap.isRecycled) {
                        blinkBitmap = BitmapFactory.decodeFile(blinkPhoto.filePath)
                    }

                    // get shake bitmap
                    val shakePhoto = LivenessResult.getShakePhoto()
                    var shakeBitmap = shakePhoto.bitmap
                    if (shakeBitmap == null || shakeBitmap.isRecycled) {
                        shakeBitmap = BitmapFactory.decodeFile(shakePhoto.filePath)
                    }

                } else {
                    val errorMsg = LivenessResult.getErrorMsg()
                }
            }
        })
//        binding.cameraPreview.setProgressBarColor(progressBarColor)
        binding.cameraPreview.setActionList(arrayListOf(Detector.DetectionType.MOUTH, Detector.DetectionType.BLINK, Detector.DetectionType.POS_YAW))
//        binding.cameraPreview.
    }

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("hzshkj", "setupView error: $requestCode")
        if (requestCode == 100) {

            if (LivenessResult.isSuccess()) {
                // get front face bitmap
                val facePhoto = LivenessResult.getFacePhoto()
                var faceBitmap = facePhoto.bitmap
                if (faceBitmap == null || faceBitmap.isRecycled) {
                    faceBitmap = BitmapFactory.decodeFile(facePhoto.filePath)
                }

                // get mouth bitmap
                val mouthPhoto = LivenessResult.getMouthPhoto()
                var mouthBitmap = mouthPhoto.bitmap
                if (mouthBitmap == null || mouthBitmap.isRecycled) {
                    mouthBitmap = BitmapFactory.decodeFile(mouthPhoto.filePath)
                }

                // get blink bitmap
                val blinkPhoto = LivenessResult.getBlinkPhoto()
                var blinkBitmap = blinkPhoto.bitmap
                if (blinkBitmap == null || blinkBitmap.isRecycled) {
                    blinkBitmap = BitmapFactory.decodeFile(blinkPhoto.filePath)
                }

                // get shake bitmap
                val shakePhoto = LivenessResult.getShakePhoto()
                var shakeBitmap = shakePhoto.bitmap
                if (shakeBitmap == null || shakeBitmap.isRecycled) {
                    shakeBitmap = BitmapFactory.decodeFile(shakePhoto.filePath)
                }

            } else {
                val errorMsg = LivenessResult.getErrorMsg()
            }
        }
    }

    fun getPermissions() {
        val permissions = listOf(CAMERA).toTypedArray()
        PermissionUtils.permission(*permissions)
            .rationale { _, shouldRequest ->
                run {
                    shouldRequest.again(true)
                }
            }.callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: MutableList<String>) {
                    Log.d("hzshkj", "onGranted: $permissionsGranted")
                }

                override fun onDenied(forever: MutableList<String>, denied: MutableList<String>) {
                    if (forever.isNotEmpty()) {
                        AppUtils.launchAppDetailsSettings()
                    } else {
                        getPermissions()
                    }
                }
            }).request()
    }

}