package com.dlc.chemical.serial.usb.steelyard

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.usb.UsbManager
import android.os.Handler
import android.os.Looper
import com.dlc.chemical.R
import com.dlc.chemical.iflytek.AudioPlayerManager
import com.dlc.chemical.serial.listener.OnSerialListener
import com.dlc.chemical.serial.usb.AbsUsbSerialManager
import com.rc.core.log.RcLog
import com.rc.core.util.Weak

/**
 * info
 *
 * @author ReiChin_
 */
class SteelyardHelper(context: Context, private val listener: OnSteelyardListener? = null) {

    private val mContext: Context? by Weak { context }

    interface OnSteelyardListener {
        fun showToast(message: String)
        fun refreshWeight(weight: String)
        fun refreshTips(tipsResId: Int)
        fun refreshViewStatus(cmdFn: String)
    }

    fun onResume() {
        registerSteelyardBroadcastReceiver()

        pauseWeighing = false
        if (!stopWeighing) {
            mPrevWeight = ""
        }
        if (mSteelyardManager.usbPermission == AbsUsbSerialManager.UsbPermission.Unknown
            || mSteelyardManager.usbPermission == AbsUsbSerialManager.UsbPermission.Granted
        ) {
            mContext?.let { mSteelyardManager.connect(it) }
        }
    }

    fun onPause() {
        pauseWeighing = true
        if (mSteelyardManager.connected) {
            RcLog.warn("SteelyardHelper#onPause() steelyard usb device disconnected.")
            mSteelyardManager.disconnect()
        }
        if (null != mSteelyardBroadcastReceiver) {
            mContext?.unregisterReceiver(mSteelyardBroadcastReceiver)
            mSteelyardBroadcastReceiver = null
        }
    }

    var pauseWeighing = false // 暂停称重
    var stopWeighing = false // 停止称重

    private val mSteelyardManager by lazy {
        SteelyardManager(object : OnSerialListener {
            override fun onConnected(success: Boolean, message: String?) {
                RcLog.info("SteelyardHelper: onConnected() success=${success}, message=${message}, mStopWeighing=${stopWeighing}, mPauseWeighing=${pauseWeighing}")
                if (stopWeighing) return

                if (success) {
                    mainLooper.postDelayed({
                        listener?.refreshTips(R.string.weighing)
                        AudioPlayerManager.speakVoice(R.raw.audio_weighing)
                        sendReadWeightCMD()
                    }, 3000)
                } else {
                    if (!pauseWeighing) listener?.showToast("秤连接失败，${message}")
                }
            }

            @SuppressLint("SetTextI18n")
            override fun onReceive(content: String) {
                RcLog.info("SteelyardHelper#onReceive()>>> stopWeighing:${stopWeighing}, pauseWeighing:${pauseWeighing}")
                // 秤读数返回
                if (stopWeighing) return
                if (!pauseWeighing) {
                    listener?.refreshWeight(content)
                    if (mPrevWeight == content && "0.0" != content) {
                        // 读数稳定
                        if (!mWeightStable) {
                            // 读数由不稳定变为稳定
                            listener?.refreshTips(R.string.weight_completed)
                            AudioPlayerManager.speakVoice(R.raw.audio_weight_completed)
                        }
                        mWeightStable = true
                    } else {
                        listener?.refreshTips(R.string.weighing)
//                        AudioPlayerManager.speakVoice(R.raw.audio_weighing)
                        mWeightStable = false
                    }
                    mPrevWeight = content
                }
                sendReadWeightCMD()
            }

            override fun onReceiveCmd(cmdFn: String, content: String?) {
                listener?.refreshTips(R.string.weighing)
                listener?.refreshViewStatus(cmdFn)
                stopWeighing = false
                sendReadWeightCMD()
            }

        })
    }

    private var mPrevWeight = "" // 上一次读取的重量
    private var mWeightStable = false // 重量是否稳定

    private val mainLooper: Handler = Handler(Looper.getMainLooper())

    private fun sendReadWeightCMD() {
        mainLooper.postDelayed({
            /*RcLog.info("sendWeighingCMD() stopWeighing=${stopWeighing}, pauseWeighing=${pauseWeighing}")
            if (!stopWeighing && !pauseWeighing) */mSteelyardManager.sendWeighingCMD()
        }, 1000)
    }

    private var mSteelyardBroadcastReceiver: BroadcastReceiver? = null

    private fun registerSteelyardBroadcastReceiver() {
        if (null == mSteelyardBroadcastReceiver) {
            val filter = IntentFilter(AbsUsbSerialManager.INTENT_ACTION_STEELYARD_USB)
            mSteelyardBroadcastReceiver = object : BroadcastReceiver() {
                override fun onReceive(context: Context?, intent: Intent?) {
                    if (AbsUsbSerialManager.INTENT_ACTION_STEELYARD_USB == intent!!.action) {
                        mSteelyardManager.usbPermission = if (intent.getBooleanExtra(
                                UsbManager.EXTRA_PERMISSION_GRANTED,
                                false
                            )
                        ) AbsUsbSerialManager.UsbPermission.Granted else AbsUsbSerialManager.UsbPermission.Denied
                        mContext?.let { mSteelyardManager.connect(it) }
                    }
                }

            }
            mContext?.registerReceiver(mSteelyardBroadcastReceiver, filter)
        }
    }

    /**
     * 发送去皮CMD
     */
    fun sendPeelCMD() {
        mainLooper.removeCallbacksAndMessages(null)
        stopWeighing = true
        listener?.refreshTips(R.string.weight_peeling)
        mainLooper.postDelayed({
            mSteelyardManager.sendPeelCMD()
        }, 100)
    }

}