package com.dlc.eboard.finger

import android.content.*
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.*
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.eyecool.fp.client.Callback
import com.rc.core.log.RcLog
import com.rc.httpcore.vo.response.UserFingerVo

/**
 * info
 *
 * @author ReiChin_
 */
class FingerHelper(private val listener: OnFingerListener? = null) :
    LifecycleEventObserver {

    private var mFingerBinder: FingerService.FingerBinder? = null

    private val mFingerConnection: ServiceConnection = object : ServiceConnection {

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            mFingerBinder = service as FingerService.FingerBinder
        }

        override fun onServiceDisconnected(name: ComponentName) {
        }
    }

    fun enroll(callback: Callback, timeout: Int = 30000) {
        mFingerBinder?.enroll(callback, timeout)
    }

    fun enrollByFeature(callback: Callback, timeout: Int = 5000) {
        mFingerBinder?.enrollByFeature(callback, timeout)
    }

    fun lazyVerify() {
        mFingerBinder?.lazyVerify()
    }

    fun verify() {
        mFingerBinder?.verify()
    }

    private var mFingerBroadcastReceiver: BroadcastReceiver? = null

    private fun registerFingerBroadcastReceiver(context: Context) {
        if (null == mFingerBroadcastReceiver) {
            val filter = IntentFilter().apply {
                addAction(FingerService.ACTION_TOAST)
                addAction(FingerService.ACTION_MATCH_SUCCESS)
                addAction(FingerService.ACTION_MATCH_FAILURE)
                addAction(FingerService.ACTION_MATCH_LOOP)
            }
            mFingerBroadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    when (intent?.action) {
                        FingerService.ACTION_TOAST -> {
                            val message = intent.getStringExtra("message")!!
                            RcLog.info("[finger] FingerHelper#onReceive() TOAST message=${message}")
                            listener?.showToast(message)
                        }
                        FingerService.ACTION_MATCH_SUCCESS -> {
                            val data = intent.getParcelableExtra<UserFingerVo>("data")!!
                            RcLog.info("[finger] FingerHelper#onReceive() MATCH_SUCCESS data=${data}")
                            if (true == listener?.onMatchSuccess(data)) {
                                verify()
                            }
                        }
                        FingerService.ACTION_MATCH_FAILURE -> {
                            val message = intent.getStringExtra("message")!!
                            RcLog.info("[finger] FingerHelper#onReceive() MATCH_FAILURE message=${message}")
                            listener?.onMatchFailure(message)
                        }
                        FingerService.ACTION_MATCH_LOOP -> {
                            RcLog.info("[finger] FingerHelper#onReceive() MATCH_LOOP")
                            listener?.loopMatch()
                        }
                    }
                }
            }
            LocalBroadcastManager.getInstance(context)
                .registerReceiver(mFingerBroadcastReceiver!!, filter)
        }
    }

    private fun onCreate(context: Context) {
        val intent = Intent(context, FingerService::class.java)
        context.bindService(intent, mFingerConnection, Context.BIND_AUTO_CREATE)
    }

    private fun onResume(context: Context) {
        registerFingerBroadcastReceiver(context)
    }

    private fun onPause(context: Context) {
        mFingerBroadcastReceiver?.let { receiver ->
            LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver)
        }
        mFingerBroadcastReceiver = null
    }

    private fun onDestroy(context: Context) {
        context.unbindService(mFingerConnection)
    }

    override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
        val context: Context = when (source) {
            is AppCompatActivity -> source
            is Fragment -> source.requireContext()
            else -> return
        }
        when (event) {
            Lifecycle.Event.ON_CREATE -> onCreate(context)
            Lifecycle.Event.ON_RESUME -> onResume(context)
            Lifecycle.Event.ON_PAUSE -> onPause(context)
            Lifecycle.Event.ON_DESTROY -> onDestroy(context)
            else -> return
        }
    }

}