package com.gh.gamecenter.common.observer

import android.content.Context
import android.database.ContentObserver
import android.media.AudioManager
import android.os.Handler
import com.gh.gamecenter.common.HaloApp
import com.gh.gamecenter.common.utils.tryCatchInRelease

class VolumeObserver(var callback: MuteCallback? = null) : ContentObserver(Handler()) {
    var previousVolume: Int = 0

    init {
        val audio = HaloApp.getInstance().getSystemService(Context.AUDIO_SERVICE) as AudioManager
        // 部分设备的 audioManager getStreamVolume 内部会触发空指针 :(
        tryCatchInRelease { previousVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC) }
    }

    override fun onChange(selfChange: Boolean) {
        super.onChange(selfChange)

        val audio = HaloApp.getInstance().getSystemService(Context.AUDIO_SERVICE) as AudioManager
        var currentVolume = 0

        tryCatchInRelease {
            // 部分设备(Meizu 7.1.2 M6 Note)的 audioManager getStreamVolume 内部会触发空指针 :(
            currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC)
        }

        val delta = previousVolume - currentVolume

        if (delta != 0) {
            if (currentVolume == 0) {
                callback?.onMute(true)
            } else {
                callback?.onMute(false)
            }
        }

        if (delta > 0) {
            previousVolume = currentVolume
        } else if (delta < 0) {
            previousVolume = currentVolume
        }
    }
}

interface MuteCallback {
    fun onMute(isMute: Boolean)
}