package com.yidian.shenghuoquan.newscontent.audio

import android.app.Service
import android.content.Intent
import android.graphics.PixelFormat
import android.os.Build
import android.os.IBinder
import android.util.Log
import android.view.*
import android.view.WindowManager.LayoutParams.*
import androidx.core.view.isGone
import com.yidian.shenghuoquan.newscontent.utils.audioManager
import com.yidian.shenghuoquan.newscontent.widget.FloatAudioView

/**
 * 主要控制音频的生命周期
 */
class AudioService : Service() {
    private  val TAG = "AudioService"

    private var windowManager:WindowManager?=null
    private lateinit var rootView: FloatAudioView

    override fun onCreate() {
        super.onCreate()
        windowManager = getSystemService(WINDOW_SERVICE) as WindowManager?
        rootView = FloatAudioView(this)

        rootView.setPlayEnable(false)
        audioManager.prepareAsync { result,_->
            Log.e(TAG, "onCreate: prepare$result" )
            if (result){
                rootView.setContent("第一首歌")
                rootView.setPlayEnable(true)
            }
        }
        audioManager.setOnErrorListener {
            Log.e(TAG, "onError: =========" )

        }
        rootView.setOnCloseListener {
            stopSelf()
        }
    }
    override fun onBind(intent: Intent): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        showFloatingWindow()
        return START_STICKY
    }

    private fun showFloatingWindow(){
        val params = WindowManager.LayoutParams()

        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            params.type = TYPE_APPLICATION_OVERLAY
        }else{
            params.type = TYPE_PHONE
        }
        params.packageName = packageName
        params.flags = params.flags or FLAG_HARDWARE_ACCELERATED
        params.flags = params.flags or FLAG_NOT_FOCUSABLE or FLAG_NOT_TOUCH_MODAL

        params.flags = params.flags or FLAG_LAYOUT_INSET_DECOR or FLAG_LAYOUT_IN_SCREEN
        params.width = MATCH_PARENT
        params.height = WRAP_CONTENT
        params.format = PixelFormat.TRANSPARENT
        params.gravity = Gravity.BOTTOM
        params.x = 0
        params.y = 500
        windowManager?.addView(rootView,params)
        audioManager.bindAudioView(rootView)

    }

    override fun onDestroy() {
        super.onDestroy()
        rootView.isGone = true
        windowManager?.removeView(rootView)
        windowManager =null
        audioManager.release()

    }


}