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

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import com.dlc.eboard.LabApp
import com.dlc.eboard.databinding.FragmentAuthFaceMatchingBinding
import com.dlc.eboard.ui.auth.AuthType
import com.dlc.eboard.ui.auth.OnAuthResultListener
import com.rc.core.ui.fragment.RcBaseFragment
import com.rc.core.util.MediaUtils
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.exception.NetException
import io.fotoapparat.Fotoapparat
import io.fotoapparat.facedetector.processor.FaceDetectorProcessor
import io.fotoapparat.log.fileLogger
import io.fotoapparat.log.logcat
import io.fotoapparat.log.loggers
import io.fotoapparat.selector.back
import io.fotoapparat.selector.front
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * 人脸识别
 *
 * @author ReiChin_
 */
class FaceAuthFragment :
    RcBaseFragment<FragmentAuthFaceMatchingBinding>() {

    companion object {
        const val TAG = "FaceAuthFragment"

        private const val WHAT_TAKE_PICTURE = 1
        private const val TIMEOUT_TAKE_PICTURE = 2000L

        fun newInstance() = FaceAuthFragment()
    }

    private var isMatching = false
    private lateinit var mFotoapparat: Fotoapparat

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

    override fun initViews(savedInstanceState: Bundle?) {
        isMatching = false
        mFotoapparat = Fotoapparat.with(requireContext())
            .into(viewBinding.cameraView)
//            .lensPosition(front())
            .lensPosition(back())
            .frameProcessor(
                FaceDetectorProcessor.with(requireContext())
                    .listener { faces ->
                        viewBinding.rectanglesView.setRectangles(faces)
//                        if (!isMatching && isResumed && !faces.isNullOrEmpty()) takePicture()
                        if (!isMatching && isResumed) {
                            isMatching = true
                            mTakePictureHandler.sendEmptyMessageDelayed(WHAT_TAKE_PICTURE, TIMEOUT_TAKE_PICTURE)
                        }
                    }.build()
            )
            .logger(loggers(logcat(), fileLogger(requireContext())))
            .build()
    }

    private val mTakePictureHandler = object : Handler(Looper.getMainLooper()) {

        override fun handleMessage(msg: Message) {
            if (!isResumed) return
            if (WHAT_TAKE_PICTURE == msg.what) takePicture()
        }
    }

    private fun takePicture() {
//        isMatching = true
        val format = SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.getDefault())
        val fileName = "${format.format(Calendar.getInstance().time)}.jpg"
        val photoFile = File(requireContext().getExternalFilesDir("photos"), fileName)
        mFotoapparat.takePicture()
            .saveToFile(photoFile)
            .whenAvailable {
                callFaceMatchingApi(photoFile)
            }
    }

    override fun onResume() {
        super.onResume()
        mFotoapparat.start()
        isMatching = false
    }

    override fun onPause() {
        super.onPause()
        mFotoapparat.stop()
        mTakePictureHandler.removeCallbacksAndMessages(null)
    }

    private fun callFaceMatchingApi(photoFile: File) {
        if (!photoFile.exists()) return
        val disposable = ApiRepository.authFace(photoFile, LabApp.sLabConfig!!.labId)
            .subscribe({ userVo ->
                MediaUtils.deleteFile(photoFile)
                if (!isResumed) return@subscribe

                val activity = requireActivity()
                if (activity is OnAuthResultListener) {
                    if (!activity.onAuthSuccess(AuthType.FACE, userVo)) {
                        isMatching = false
                    }
                }
            }, { throwable ->
                MediaUtils.deleteFile(photoFile)
                if (!isResumed) return@subscribe

                if (!pretreatmentError(throwable)) {
                    isMatching = false
                    throwable.printStackTrace()
                    showNetError(throwable)
                }
            })
        addDisposable(disposable)
    }

    private fun pretreatmentError(throwable: Throwable): Boolean {
        if (throwable is NetException) {
            if ("500" == throwable.code &&
                true == throwable.message?.startsWith("人脸对比不符")
            ) {
                // 500- 人脸对比不符！
                AlertDialog.Builder(requireContext())
                    .setCancelable(false)
                    .setTitle("提示")
                    .setMessage(throwable.message)
                    .setPositiveButton("确定") { _, _ ->
                        isMatching = false
                    }.show()
                return true
            } else if ("500" == throwable.code
                && throwable.message == "识别中") {
                isMatching = false
                return true
            }
        }
        return false
    }

}