package com.casic.electric.detector.view

import android.content.Context
import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.KeyEvent
import com.casic.electric.detector.R
import com.casic.electric.detector.base.SerialPortActivity
import com.casic.electric.detector.extensions.initLayoutImmersionBar
import com.casic.electric.detector.utils.GpioManager
import com.gyf.immersionbar.ImmersionBar
import com.pengxh.kt.lite.extensions.convertColor
import com.pengxh.kt.lite.utils.WeakReferenceHandler
import kotlinx.android.synthetic.main.activity_install_small_label.*
import kotlinx.android.synthetic.main.include_base_title.*

class InstallSmallLabelActivity : SerialPortActivity(), Handler.Callback {

    private val kTag = "SmallLabelActivity"
    private val context: Context = this@InstallSmallLabelActivity
    private val gpioManager by lazy { GpioManager() }
    private var soundResId = 0
    private lateinit var weakReferenceHandler: WeakReferenceHandler
    private lateinit var soundPool: SoundPool

    override fun initLayoutView(): Int = R.layout.activity_install_small_label

    override fun setupTopBarLayout() {
        titleView.text = "安装新电子标签"
        titleView.setTextColor(R.color.themeColor.convertColor(this))

        ImmersionBar.with(this)
            .statusBarDarkFont(true)
            .statusBarColor(R.color.mainBackground)
            .init()
        initLayoutImmersionBar(rootView)
    }

    override fun initData(savedInstanceState: Bundle?) {
        weakReferenceHandler = WeakReferenceHandler(this)

        val audioAttributes = AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .build()
        soundPool = SoundPool.Builder()
            .setMaxStreams(16)
            .setAudioAttributes(audioAttributes)
            .build()
    }

    override fun observeRequestState() {

    }

    override fun initEvent() {

    }

    override fun onDataReceived(buffer: ByteArray?, size: Int) {
        Log.d(kTag, "onDataReceived => " + buffer.contentToString())
        if (buffer != null) {
            val message = weakReferenceHandler.obtainMessage()
            message.what = 2023081702
            message.obj = buffer
            weakReferenceHandler.sendMessage(message)
        }
    }

    override fun handleMessage(msg: Message): Boolean {
        if (msg.what == 2023081702) {

        }
        return true
    }

    override fun onDestroy() {
        soundPool.release()
        gpioManager.setGpioLow("18")
        super.onDestroy()
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            soundPool.release()
        }
        return super.onKeyDown(keyCode, event)
    }
}